ng-repeat not working over collections that contains dupes

odwl picture odwl · Dec 8, 2013 · Viewed 8.9k times · Source

The following code is not working because the collection contains dupes:

<div ng-repeat="value in [4, 4]"></div>

I think that the following should work but is unfortunately not working:

<div ng-repeat="value in [4, 4] track by $index"></div>

Is that a bug?

Is there a way to use ng-repeat over a collection that contains dupes?

Thanks in advance,

Olivier

Answer

Kia Panahi Rad picture Kia Panahi Rad · Dec 8, 2013

This feature has been added to AngularJS in newer versions. the point is that basically you should not iterate over some primitive types (e.g. numbers) but over some complex objects.

from what I've understood the ngRepeat directive checks the references not the actual values so if you iterate over some complex objects it woks but if you try to do that over a set of primitive types it will most likely not work as long as "all" the values differ from one another.

EDIT

The following lines are copies and pasted from this link (and make sure you are using a relatively up-to-date version of AngularJS - I'm using 1.1.5 and it's working perfectly -)

Description

Occurs if there are duplicate keys in an ngRepeat expression. Duplicate keys are banned because AngularJS uses keys to associate DOM nodes with items.

By default, collections are keyed by reference which is desirable for most common models but can be problematic for primitive types that are interned (share references).

For example the issue can be triggered by this invalid code:

<div ng-repeat="value in [4, 4]">
</div>

To resolve this error either ensure that the items in the collection have unique identity of use the track by syntax to specify how to track the association between models and DOM.

To resolve the example above can be resolved by using track by $index, which will cause the items to be keyed by their position in the array instead of their value:

<div ng-repeat="value in [4, 4] track by $index"></div>