each time click "add item" button repeatedly adds item items array. example, if click "add item" 5 times array is:
items: [item, item, item, item, item] how can modify code add first item not add additional items array, so:
items: [item] i tried replacing var = -1 var = 0 never adds item items array.
here's 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 () { (var = -1; < $scope.items.length; i++) { if ($scope.items[i] != $scope.item) { $scope.items.push($scope.item); } } }; }); here's plunker: http://plnkr.co/edit/ot900pxecxggkpjzna2x?p=preview
add simple validation
in additem(), add simple validation using indexof check if item in array:
$scope.additem = function () { if ($scope.items.indexof($scope.item) != -1){ // item in array, abort! return; } $scope.items.push($scope.item); }
Comments
Post a Comment