angularjs – 当数组中的对象列表时,重复不允许在ng-repeat中出错

前端之家收集整理的这篇文章主要介绍了angularjs – 当数组中的对象列表时,重复不允许在ng-repeat中出错前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很困惑为什么ng-repeat给我重复错误.我可以使用track by $index来解决它,但我想知道何时由angular引发此错误.

这很清楚

<div ng-repeat="a in [1,1,1]">...</div>

由于上面的数组中存在重复值,因此肯定会抛出Dups错误.

对象列表怎么样?

<div ng-repeat="a in items">...</div>

JS

$scope.items = [
                   {"ab":1,"bc":3},{"ab":1,"bc":3}
               ]

角度如何处理/比较第二个以确定是否存在重复值?

谢谢.

编辑

为什么我没有出现重复错误

Fiddle DEMO

解决方法

请参阅本教程 http://www.anujgakhar.com/2013/06/15/duplicates-in-a-repeater-are-not-allowed-in-angularjs/.

在您的情况下,因为您的两个对象具有相同的键值(ab),您将收到错误.通过$index添加曲目可能会解决问题.

编辑

从源代码.

variable in expression track by tracking_expression` – You can also provide an optional tracking function
* which can be used to associate the objects in the collection with the DOM elements. If no tracking function
* is specified the ng-repeat associates elements by identity in the collection. It is an error to have
* more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
* mapped to the same DOM element,which is not possible.) Filters should be applied to the expression,
* before specifying a tracking expression.

据我了解,重复中的两个元素解析为相同的跟踪id(我相信$$hashkey)你会得到错误.你应该看看他们的源代码.它的评论和注释都很好.

猜你在找的Angularjs相关文章