我有这个。
var studentsList = [
{"Id": "101", "name": "One"},
{"Id": "101", "name": "One"},
{"Id": "102", "name": "Two"},
{"Id": "103", "name": "Three"},
{"Id": "103", "name": "Three"},
{"Id": "104", "name": "Four"},
{"Id": "104", "name": "Four"}
];
我想切换,单击时从此对象中删除重复项。
<button ng-click="removeDuplicates = !removeDuplicates"></button>
我该怎么做,有什么想法吗?
预先感谢 :)
angular.module('app', [])
.controller('MyController', ['$scope', function($scope) {
$scope.studentsList = [
{"Id": "101", "name": "One"},
{"Id": "101", "name": "One"},
{"Id": "102", "name": "Two"},
{"Id": "103", "name": "Three"},
{"Id": "103", "name": "Three"},
{"Id": "104", "name": "Four"},
{"Id": "104", "name": "Four"}
];
}]).filter('dupfilter',function(){
var cache = {};
return function(array, dup){
if(dup)
return array;
var key = JSON.stringify(array);
if(cache[key])
return cache[key];
var temp = [];
for(var item of array){
item.$$hashKey = undefined;
var str = JSON.stringify(item);
if(temp.indexOf(str) == -1)
temp.push(str);
}
var result = [];
for(var item of temp)
result.push(JSON.parse(item));
cache[key] = result;
return result;
}
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-controller="MyController">
<input type='button' value='{{(removeDuplicates ? "Allow" : "Remove") + " duplicates"}}' ng-click='removeDuplicates=!removeDuplicates'/>
<ul>
<li ng-repeat='item in studentsList | dupfilter: !removeDuplicates'>{{item | json}}</li>
</ul>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句