AngularJs 删除 ng-repeat 中的重复元素 [英] AngularJs Remove duplicate elements in ng-repeat
问题描述
我有一本字典存储在 field_detail
<li ng-repeat = "field in field_detail">{{field.displayName}}</li>
现在我不想包含重复的 field_detail
的 displayName
,我应该使用什么 filter
?
Now I dont want to include duplicate displayName
of field_detail
, what filter
should I use?
推荐答案
只需创建一个过滤器来获取唯一值,可能是通过一个键.应该做这样的事情(我根本没有测试这个,所以我会把这个事情留给你,这只是给你一个想法):
Just create a filter that gets the unique values, probably by a key. Something like this ought to do (I didn't test this at all, so I'll leave that business to you, this is just to give you an idea):
app.filter('unique', function() {
return function(collection, keyname) {
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
});
<div ng-repeat="item in items | unique: 'id'"></div>
注意:Array.indexOf() 在 IE8 中不起作用,所以如果你支持 IE8,你需要在 indexOf() 中存根,或者你需要使用一个方法略有不同.
Note: Array.indexOf() does not work in IE8, so if you're supporting IE8, you'll need to stub in indexOf(), or you'll need to use a slightly different approach.
其他想法:如果您已经在引用这些库,最好创建一个过滤器来利用低破折号或下划线中的独特功能.
Other thoughts: It's probably better just to create a filter that leverages the unique function in lowdash or underscore if you're already referencing those libraries.
这篇关于AngularJs 删除 ng-repeat 中的重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!