1

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

6
  • Did you try if $scope.items.indexOf($scope.item) != -1 than push item in array? Commented Jul 9, 2015 at 19:31
  • Do you only want to push one time (on the first time)? Commented Jul 9, 2015 at 19:32
  • What is your rationale behind using $scope.items[i] when i is -1? What is that supposed to achieve? Commented Jul 9, 2015 at 19:36
  • @Amit Yes, just one at a time. Commented Jul 9, 2015 at 19:54
  • @doldt It was just for troubleshooting. If I set it to 0 (instead of -1) it returned nothing. Commented Jul 9, 2015 at 19:54

2 Answers 2

3

Add a simple validation

In addItem(), add a simple validation using indexOf to check if the item is in the array:

$scope.addItem = function () {

    if ($scope.items.indexOf($scope.item) != -1){
      // The item is already in the array, abort!
      return;
    }

    $scope.items.push($scope.item);
}

http://plnkr.co/edit/GKtREKBXUD7J54oxTaDq?p=preview

Sign up to request clarification or add additional context in comments.

Comments

3

Here's a forked version of your plunkr.

It uses indexOf, which is a built-in function to tell whether an array contains an elment or not (it returns -1 when the item is not found):

$scope.addItem = function () {
  if($scope.items.indexOf($scope.item) === -1){
      $scope.items.push($scope.item);
  }
};

I'm not sure what were you trying to achieve by referencing $scope.items[-1], care to elaborate?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.