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

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

问题描述

以下代码不起作用,因为该集合包含欺骗:

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

我认为以下应该有效,但不幸的是不起作用:

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

这是一个错误吗?

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

提前致谢,

奥利维尔

解决方案

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

据我所知,ngRepeat 指令检查引用而不是实际值,因此如果您遍历一些复杂的对象,它会起作用,但是如果您尝试在一组原始类型上这样做只要所有"值彼此不同,就很可能不起作用.

编辑

以下几行是从 此链接 中复制和粘贴的(并确保您正在使用相对最新版本的 AngularJS - 我使用的是 1.1.5 并且它运行良好 -)

<块引用>

说明

在 ngRepeat 表达式中存在重复键时发生.禁止重复键,因为 AngularJS 使用键将 DOM 节点与项目相关联.

默认情况下,集合按引用键控,这对于大多数常见模型是可取的,但对于内部的原始类型(共享引用)可能会出现问题.

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

要解决此错误,请确保集合中的项目具有唯一标识,使用 track by 语法指定如何跟踪模型和 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 不能处理包含欺骗的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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