我正在使用Angular Js开发一个web应用程序。我想填充一个div,到我的html视图,使用ng-repeat指令。ng-repeat使用的数组有一些重复项,但在我的视图中,我希望只显示一项(如果一个元素已经显示过,那么它的副本必须以图形方式隐藏)。我该怎么做呢?
<div ng-repeat="item in selectedProcedures track by $index">
<span>{{item.id}}</span>
</div>
就像这样使用一个唯一的过滤器:
<div ng-repeat="item in selectedProcedures track by $index | unique : 'id'">
<span>{{item.id}}</span>
</div>
然后创建唯一的过滤器:
app.filter('unique', function() {
return function(collection, property) {
var output = [];
angular.forEach(collection, function(item) {
//check if it exists in output on the basis of property, if not then add to output
output.push(item);
})
return output;
}
})
函数中的'property'在示例中是'id',而collection指的是整个数组。
我建议您不要隐藏生成的Html,而是添加一个过滤器来删除重复项:
<div ng-repeat="item in selectedProcedures track by $index | deleteDuplicates">
. . .
</div>
angular.module('myApp').filter('deleteDuplicates', function(){
return function filterCore(source)
{
var out = [];
// . . .
return(out);
};
});
下面是AngularJS自定义过滤器教程