ng-repeat不能处理包含dupes的集合 [英] ng-repeat not working over collections that contains dupes

查看:92
本文介绍了ng-repeat不能处理包含dupes的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无效,因为集合包含dupes:

 < div ng-repeat = 4,4]>< / div> 

我认为以下应该工作,但不幸的是不工作:

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

这是错误吗?



有没有办法在包含dupes的集合上使用 ng-repeat



Olivier

解决方案

此功能已添加到AngularJS的新版本。
关键是,基本上你不应该迭代一些原始类型(例如数字),而是一些复杂的对象。



从我理解的 ngRepeat 指令检查引用而不是实际值,所以如果你迭代一些复杂的对象它woks,但如果你试图这样做一组原始类型,它很可能不工作



EDIT

>以下行是从此链接复制和粘贴的(并确保您使用的是一个相对最新版本的AngularJS - 我使用1.1.5,它的工作完美)




如果ngRepeat表达式中存在重复的键,则会发生此错误。重复键被禁止,因为AngularJS使用键将DOM节点与项目相关联。



默认情况下,集合通过引用键入,这对于大多数常见模型是可取的,



例如,此问题可能由此无效代码触发:

 < div ng-repeat =[4,4]中的值> 
< / div>

要解决此错误,请确保集合中的项目具有通过语法使用轨道的唯一标识以指定如何跟踪模型和DOM之间的关联。



要解决上面的示例可以通过使用track by $ index来解决,这将导致项目被键入

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



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

解决方案

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>

这篇关于ng-repeat不能处理包含dupes的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆