2

I came across this code:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<script>
var app = angular.module("myShoppingList", []); 
app.controller("myCtrl", function($scope) {
    $scope.products = ["Milk", "Bread", "Cheese"];
    // If I push a duplicate here, it will crash
});
</script>

<div ng-app="myShoppingList" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="x in products">{{x}}<span ng-click="removeItem($index)">×</span></li>
  </ul>
  <input ng-model="addMe">
  <button ng-click="addItem()">Add</button>
</div>

<p>Click the little x to remove an item from the shopping list.</p>

</body>
</html>

which runs OK. However, if I push a duplicate element in the array, like this:

$scope.products.push("Milk");

the application will crash. Why is that?


  1. Same behavior if I statically initialize an array with a duplicate.
  2. Sets are with curly brackets, so I don't get this.
3
  • do this ng-repeat="x in products track by $index", angular ng-repeat does not allow duplicate Commented Jun 28, 2017 at 15:09
  • See AngularJS Error Reference - ngRepeat:dupes Commented Jun 28, 2017 at 17:19
  • I see CharlieNg! Thank you @georgeawg, interesting link! Commented Jun 28, 2017 at 19:45

1 Answer 1

3

If there are some duplicates in your array, you need to track them. Use track by $index in your ng-repeat like this:

<li ng-repeat="x in products track by $index">

This should solve your problem. For more information you can look through docs for ng-repeat (Tracking and Duplicates).

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

2 Comments

So the problem is not the array but the ng-repeat? I would like an explanation though, why this happens' why my ng-repeat crashes and yours does not?
@gsamaras, yes, if there are some duplicates in your array, you need to track them. For more information you can look through docs for ng-repeat ("Tracking and Duplicates"): docs.angularjs.org/api/ng/directive/ngRepeat

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.