ng-repeat 使用 track by $index 时与 filter 过滤冲突解决

在 angular 下使用 ng-repeat 时, 如果循环的数组中存在有重复的元素,会报错:

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)出现。而基本的数据类型它的id就是它自身的值。而解决方法就是加上 track by $index,或者也可以通过自己设置业务上的id,然后用其进行遍历track by item.id

ng-repeat="val in msg track by $index"
ng-repeat="val in msg track by val.id"

OK,这样就能解决循环数组重复的问题,不过当使用track by $index后,又会引出一个新的问题:当数据修改时,不变数据所在的dom不被重新渲染
例如:
ng-repeat 循环列表加入 track-by 后,再使用 filter 过滤方法过滤不符合要求的列表项,会发现 msg 数组中的值并没有被过滤。

ng-repeat="val in msg track by val.id | filter:storeIDStoresFilter"

而翻看 angular 文档,发现需要将track by $index作为最后一个表达式,才能完成渲染。

ng-repeat="val in msg | filter:storeIDStoresFilter track by val.id"

OK,过滤渲染成功

你可能感兴趣的:(ng-repeat 使用 track by $index 时与 filter 过滤冲突解决)