Loop in AngularJS not working
I am trying a simple AngularJS loop using the "ng-repeat" directive as shown below:
<div ng-app="" ng-init="numbers=[1,3,5,2]">
<ul>
<li ng-repeat="item in numbers">{{ item }}</li>
</ul>
</div>
The result of this as shown below is ideal
- 1
- 3
- five
- 2
However, when I change the 'numbers' array like this
<div ng-app="" ng-init="numbers=[1,3,5,2,2]">
is the rest as it is, it doesn't work.
The only change I made was that I added one more item to the array of numbers '2'. I figured out that whenever an item is repeated in the array (in this case "2") a problem occurs.
The console log I noticed looks like below
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.14/ngRepeat/dupes?p0=item%20in%20numbers&p1=number%3A2&p2=2
at Error (native)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:6:417
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:232:494
at Object.fn (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:122:53)
at l.$get.l.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:123:138)
at l.$get.l.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:126:58)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:17:479
at Object.e [as invoke] (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:36:315)
at d (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:17:400)
at tc (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:18:179)
Also, if the array is of string type, the same problem persists as well.
For example, <div ng-app="" ng-init="names=['Bishnu', 'Sagar', 'John', 'Bishnu']">
in this case also I ran into the same problem.
This behavior in AngularJS is very strange.
Does anyone know the reason and how to solve it?
source to share
Try it...
The directive ngRepeat
instantiates the template once for an item from the collection. Each template instance gets its own scope, where the specified loop variable is set to the current item in the collection, and the item's $index
index or key.
ngRepeat
makes appropriate changes to the DOM
When an element is added, a new template instance is added to the DOM. When an element is removed, its template instance is removed from the DOM. When elements are reordered, their respective templates are reordered in the DOM. By default, ngRepeat does not allow duplicate elements in arrays. This is because, when there are duplicates, it is not possible to maintain a one-to-one mapping between collection elements and DOM elements.
If you need to repeat repeating elements, you can replace the default tracking behavior with your own using track with the expression
<div ng-repeat="n in [42, 42, 43, 43] track by $index">
{{n}}
</div>
source to share