ng-repeat track by $index 如果相似键在 angularjs 中多次存在,则仅显示该项目一次
ng-repeat track by $index display the item only once if the similar key exists multiple times in angularjs
我的 angularjs 代码出现 [ngRepeat:dupes]: 错误。
所以我在 Whosebug 上搜索并找到了声明使用 $index 跟踪的解决方案。这现在对我有用。但是,如果多次出现相同的键,它会多次显示该项目。如果同一个键多次存在,我只想显示一个项目。
这是我在视图中的示例代码:
<div ng-repeat="user in users | filter:myFilter track by $index">
</div>
这是当前输出:
为了显示这两张卡片,我希望代码只显示一张卡片,因为它们是相同的。
我该怎么做?
将数组传递给函数并创建一个没有重复值的数组
像 myFunction(users) 这样重复部分将变成 ng-repeat="user in myFunction(users)"。自己写函数。
我通过创建过滤器修复了它:
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>
我的 angularjs 代码出现 [ngRepeat:dupes]: 错误。 所以我在 Whosebug 上搜索并找到了声明使用 $index 跟踪的解决方案。这现在对我有用。但是,如果多次出现相同的键,它会多次显示该项目。如果同一个键多次存在,我只想显示一个项目。 这是我在视图中的示例代码:
<div ng-repeat="user in users | filter:myFilter track by $index">
</div>
这是当前输出:
为了显示这两张卡片,我希望代码只显示一张卡片,因为它们是相同的。 我该怎么做?
将数组传递给函数并创建一个没有重复值的数组 像 myFunction(users) 这样重复部分将变成 ng-repeat="user in myFunction(users)"。自己写函数。
我通过创建过滤器修复了它:
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>