我在我的angularjs代码中遇到[ngRepeat:dupes]:错误。 因此,我在stackoverflow上进行了搜索,找到了根据$ index声明使用track的解决方案。这现在为我工作。但是,如果多次出现相同的键,它将多次显示该项目。如果同一密钥存在多次,我只想显示一项。 这是我从视图中获取的示例代码:
<div ng-repeat="user in users | filter:myFilter track by $index">
</div>
出于显示这两张卡的目的,我希望代码仅显示一张卡,因为它们都是相同的。 我该怎么办?
答案 0 :(得分:1)
将数组传递给函数并创建一个没有重复值的数组 例如 myFunction(users),因此重复部分将成为 ng-repeat =“ myFunction(users)中的用户” 。自己编写函数。
答案 1 :(得分:0)
我通过创建过滤器来解决此问题:
var app = angular.module('angularTable', []);
app.filter('unique', function() {
// we will return a function which will take in a collection
// and a keyname
return function(collection, keyname) {
// we define our output and keys array;
var output = [],
keys = [];
// we utilize angular's foreach function
// this takes in our original collection and an iterator function
angular.forEach(collection, function(item) {
// we check to see whether our object exists
var key = item[keyname];
// if it's not already part of our keys array
if(keys.indexOf(key) === -1) {
// add it to our keys array
keys.push(key);
// push this item to our final output array
output.push(item);
}
});
// return our array which should be devoid of
// any duplicates
return output;
};
});
app.controller('listdata', function($scope, $http) {
your controller logic for the users array
});
});
在视图中:
<div ng-repeat="user in users |unique:'name' | filter:myFilter track by $index">
</div>