為什么要加入track by
循環(huán)的對(duì)象是通過哈希值檢測(cè)是否一致, 當(dāng)循環(huán)發(fā)現(xiàn)兩個(gè)一樣的對(duì)象, ,js不會(huì)重復(fù)渲染. 所以當(dāng)你循環(huán)可能會(huì)出現(xiàn)重復(fù)對(duì)象,那么你需要加入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. 對(duì)比下面2個(gè)代碼强品,第一個(gè)代碼不會(huì)正常顯示, 第二個(gè)可以正常顯示.
<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