2

I am trying to learn angular-js so I created a mini app where the user adds elements in an array and the values of the array are displayed above. The app works fine but crashes when a value that already exists in the array is added.

here's the source code.

<div ng-app="myApp" ng-controller="myCtrl">

    <p>Name: <input type="text" ng-model="firstName"></p>
    <a ng-click='add(firstName)' >click me</a>

    <ul>
        <li ng-repeat="x in names">{{x}}
    </ul>
    {{msg}}
</div>

<script>
    var app = angular.module('myApp', []);

    app.controller('myCtrl', function($scope) {

        $scope.add = function(arg) {
            alert("adding:"+arg);
            $scope.names.push(arg);
        }

        $scope.names = ["Emil", "Tobias", "Linus"];
    });
</script>

</body>
</html>

here's the console error when for example I add twice the name John:

Error: [ngRepeat:dupes] http://errors.angularjs.org/1.4.8/ngRepeat/dupes?p0=x%20in%20names&p1=string%3AJohn&p2=John at Error (native) at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:6:416 at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:280:375 at Object.fn (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:130:77) at r.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:131:149) at r.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:134:78) at HTMLAnchorElement. (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:254:126) at If (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:35:367) at HTMLAnchorElement.Hf.d (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:35:314)

When this error occurs the function still works, as the alert pops up but the value of the input is not added in the array. I didn't implemented any js-fiddle because there it works fine. I use chrome browser

JmRag
  • 1,443
  • 7
  • 19
  • 56
  • Error: [ngRepeat:dupes] http://errors.angularjs.org/1.4.8/ngRepeat/dupes?p0=x%20in%20names&p1=string%3AJohn&p2=John at Error... If you follow this link you could read answer to your question. I recommend to check links which angular gives to you. – YuriyP Jan 02 '16 at 19:57

1 Answers1

3

Replace ng-repeat with:

<ul>
   <li ng-repeat="x in names track by $index">{{x}}
</ul>

AngularJS tracks by default by the value of the elements, if you have duplicates it fails. $index corresponds to the $index of names[$index] used by AngularJS when looping the array.