gpt4 book ai didi

angularjs - ng-repeat 不能处理包含欺骗的集合

转载 作者:行者123 更新时间:2023-12-03 21:54:54 28 4
gpt4 key购买 nike

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

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

我认为以下应该有效,但不幸的是不起作用:
<div ng-repeat="value in [4, 4] track by $index"></div>

这是一个错误吗?

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

提前致谢,

奥利维尔

最佳答案

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

据我所知 ngRepeat指令检查引用而不是实际值,因此如果您迭代一些复杂的对象,它会起作用,但是如果您尝试对一组原始类型执行此操作,只要“所有”值彼此不同,它很可能无法工作。

编辑

以下几行是从 this link 复制粘贴的(并确保您使用的是相对最新版本的 AngularJS - 我使用的是 1.1.5 并且它运行良好 -)

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>

关于angularjs - ng-repeat 不能处理包含欺骗的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452223/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com