AngularJS no-repeat track by 的用法

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容