Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - ng-repeat not working over collections that contains dupes

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...