美文网首页
AngularJS no-repeat track by 的用法

AngularJS no-repeat track by 的用法

作者: 南国青天 | 来源:发表于2016-12-06 11:31 被阅读103次

为什么要加入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

相关文章

网友评论

      本文标题:AngularJS no-repeat track by 的用法

      本文链接:https://www.haomeiwen.com/subject/hixrmttx.html