为什么要加入track by
循环的对象是通过哈希值检测是否一致, 当循环发现两个一样的对象, ,js不会重复渲染. 所以当你循环可能会出现重复对象,那么你需要加入track by $index
或者其他可以表示唯一的id。
To minimize creation of DOM elements, ngRepeat uses a function to "keep track" of all items in the collection and their corresponding DOM elements. For example, if an item is added to the collection, ngRepeat will know that all other items already have DOM elements, and will not re-render them.
If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.
PS. 对比下面2个代码,第一个代码不会正常显示, 第二个可以正常显示.
<div ng-repeat="n in [42, 42, 43, 43] "> {{n}}</div>
<div ng-repeat="n in [42, 42, 43, 43] track by $index"> {{n}}</div>
资料: AngularJS , Stackoverflow
网友评论