手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >AngularJS ng-repeat数组有重复值的解决方法
AngularJS ng-repeat数组有重复值的解决方法
摘要:前言大家都知道默认在ng-repeat的时候每一个item都要保证是唯一的,否则console就会打出error告诉你哪个key/value...

前言

大家都知道默认在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数组有重复值的解决方法1

点击错误链接到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数组有重复值的解决方法2

其实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数组有重复值的解决方法3

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

[] === []

总结

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

【AngularJS ng-repeat数组有重复值的解决方法】相关文章:

JavaScript数组去重的3种方法和代码实例

AngularJs中route的使用方法和配置

记录几个node.js错误及解决方案

AngularJS数据源的多种获取方式汇总

JavaScript判断数组是否包含指定元素的方法

jQuery判断一个元素是否可见的方法

JS/Jquery判断对象为空的方法

JavaScript模版引擎的基本实现方法浅析

JavaScript检测鼠标移动方向的方法

详解AngularJS中的表达式使用

精品推荐
分类导航