user1888863
user1888863

Reputation: 389

Angular JS ng-repeat/adding to array bug

I'm very new to AngularJS development, and I was testing a very simple script when I came across a bug that I can't quite decipher.

My script simply adds a string to an array from an input box when the user types something and hits enter, and below the input box, all the items are then printed out using ng-repeat.

The script seems to work fine, except when I try to add a value that is already in the list. If I add a value that has already been added again, the script stops adding items, even if I go back and try a new value.

Here is my javascript:

    var myApp = angular.module('myApp',[]);
    myApp.controller('ctrl1',function($scope){
        $scope.list = [];

        $scope.addItem = function(keyEvent){
            if(keyEvent.which === 13)
            {

                if(angular.isDefined($scope.name) && $scope.name!='')
                {
                    $scope.list.push($scope.name);
                    $scope.name = '';
                }
            }
        }

    });

And here is the html portion:

<div ng-controller = "ctrl1">
<input type = "text" ng-model = "name" placeholder = "Enter item to add to list" ng-keypress = "addItem($event)"/>
<ul ng-repeat = "item in list">
<li>{{item}}</li>
</ul>
</div>

Does anyone know what is causing this bug? Thanks

Upvotes: 2

Views: 428

Answers (1)

user2309944
user2309944

Reputation:

The default tracking function (which tracks items by their identity) does not allow duplicate items in arrays. This is because when there are duplicates, it is not possible to maintain a one-to-one mapping between collection items and DOM elements. Use track by $index to allow duplicate items in your entries. Do the following:

<div ng-controller = "ctrl1">
   <input type = "text" ng-model = "name" placeholder = "Enter item to add to list" ng-keypress = "addItem($event)"/>
   <ul ng-repeat = "item in list track by $index">
      <li>{{item}}</li>
   </ul>
</div>

Here is the documentation for ngRepeat.

Upvotes: 3

Related Questions