在 angular 下使用 ng-repeat 時, 如果循環(huán)的數(shù)組中存在有重復(fù)的元素,會報錯:
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: c in msg, Duplicate key: object:63, Duplicate value:
因為其不允許 collection 有相同的id(相同的元素會形成相同的id)出現(xiàn)。而基本的數(shù)據(jù)類型它的id就是它自身的值。而解決方法就是加上 track by $index,或者也可以通過自己設(shè)置業(yè)務(wù)上的id,然后用其進行遍歷track by item.id
ng-repeat="val in msg track by $index"
ng-repeat="val in msg track by val.id"
OK,這樣就能解決循環(huán)數(shù)組重復(fù)的問題,不過當使用track by $index后,又會引出一個新的問題:當數(shù)據(jù)修改時,不變數(shù)據(jù)所在的dom不被重新渲染
例如:
ng-repeat 循環(huán)列表加入 track-by 后,再使用 filter 過濾方法過濾不符合要求的列表項,會發(fā)現(xiàn) msg 數(shù)組中的值并沒有被過濾。
ng-repeat="val in msg track by val.id | filter:storeIDStoresFilter"
而翻看 angular 文檔,發(fā)現(xiàn)需要將track by $index作為最后一個表達式,才能完成渲染。
ng-repeat="val in msg | filter:storeIDStoresFilter track by val.id"
OK,過濾渲染成功