AngularJS ng-repeat数组有重复值的解决方法

2016-11-22 14:34:41  angular.jsng-repeat数组

前言

大家都知道默认在ng-repeat的时候每一个item都要保证是唯一的,否则console就会打出error告诉你哪个key/value是重复的。

如:

$scope.items = [ 'red', 'blue', 'yellow', 'white', 'blue' ];

这个数组blue就重复了,html这么遍历它

<li ng-repeat="item in items">{{ item }}</li>

控制台就会抛出一个错误:

AngularJS ng-repeat数组有重复值的解决方法

点击错误链接到Angular官网看详细错误,官网明确给出是因为值重复了:

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: string:blue, Duplicate value: blue

解决方法

这就纳闷了,正常的业务里数组有重复的值是很正常的,数组要硬要搞成唯一的ng-repeat才能遍历就白瞎了,继续往下看,发现官网给了一个解决的方案

<div ng-repeat="value in [4, 4] track by $index"></div>

于是按照这个方案改了一下

<li ng-repeat="item in items track by $index">{{ item }}</li>

刷新网页,内容被正常解析

AngularJS ng-repeat数组有重复值的解决方法

其实ng-repeat还是需要一个唯一的key,只不过你不track的话默认就是item本身,另外也只有在普通数据类型字符串,数字等才会出现这个问题,如果换成Object

$scope.items = [ ['red'], ['blue'], ['yellow'], ['white'], ['blue'] ];

html恢复为

<li ng-repeat="item in items">{{ item }}</li>

执行结果:

AngularJS ng-repeat数组有重复值的解决方法

不明白的童鞋那就自己看看下面的运算表达式,猜猜结果是什么,然后在浏览器的控制台试一试你的答案是否正确

[] === []

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

AngularJS ng-repeat数组有重复值的解决方法》阅读地址:http://www.haoshilao.net/12399/

最新图文教程: