Each time I click the "Add item" button it repeatedly adds item to the items array. For example, if I click "Add item" five times the array is:
items: [item, item, item, item, item]
How can I modify my code to add the first item but not add additional items to the array, like so:
items: [item]
I tried replacing var i = -1 with var i = 0 but that never adds item to the items array.
Here's my view:
<body ng-controller="MainCtrl">
<button ng-click="addItem()">Add {{item}}</button>
<p>items: {{items | json}}</p>
</body>
...and controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.item = 'item';
$scope.items = [];
$scope.addItem = function () {
for (var i = -1; i < $scope.items.length; i++) {
if ($scope.items[i] != $scope.item) {
$scope.items.push($scope.item);
}
}
};
});
Here's my Plunker: http://plnkr.co/edit/OT900pXEcxGgkpJZna2x?p=preview
pushone time (on the first time)?$scope.items[i]wheniis -1? What is that supposed to achieve?