2

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

1
  • 1
    Open the browser console. There will be a written mistake. Also, the console will display a link to the cause of the error and ways to to fix it. Commented Mar 26, 2016 at 5:43

1 Answer 1

3

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.

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

1 Comment

ahh thanks... guess it was pretty simple, it's pretty easy to miss things learning from random youtube tutorials lol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.