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

2019-11-28,,,,,

前言

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

如:

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

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

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

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

点击错误链接到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>

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

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

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

html恢复为

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

执行结果:

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

[] === []

总结

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

您可能感兴趣的文章:

  • 详解AngularJS中的filter过滤器用法
  • AngularJS中的过滤器filter用法完全解析
  • AngularJS过滤器filter用法总结
  • 详解AngularJS中$filter过滤器使用(自定义过滤器)
  • Angularjs的ng-repeat中去除重复数据的方法
  • AngularJS ng-repeat指令中使用track by子语句解决重复数据遍历错误问题
  • AngularJs验证重复密码的方法(两种)
  • AngularJS使用Filter自定义过滤器控制ng-repeat去除重复功能示例

《AngularJS ng-repeat数组有重复值的解决方法.doc》

下载本文的Word格式文档,以方便收藏与打印。