这篇文章主要介绍了angularjs使用filter自定义过滤器控制ng-repeat去除重复功能,结合实例形式分析了angularjs自定义过滤器的定义及数组过滤相关操作技巧,需要的朋友可以参考下
本文实例讲述了angularjs使用filter自定义过滤器控制ng-repeat去除重复功能。分享给大家供大家参考,具体如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>www.jb51.net ng-repeat去除重复</title>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<p ng-app="myapp" ng-controller="myctrl">
<p ng-repeat="x in items | unique:'id'">
{{x.id}}---{{x.name}}
</p>
</p>
<script>
//angularjs 自定义过滤器
//1.使用过滤器,去除重复
angular.module('common', []).filter('unique', function () {
return function (collection, keyname) {
console.info(collection);
console.info(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;
}
});
var app = angular.module('myapp', ['common']);
app.controller('myctrl', function ($scope) {
//$scope.items = [1, 2, 3,2];
//当前unique 的过滤只针对,对象数组过滤
$scope.items = [
{ id: 1, name: 'zhangsan' },
{ id: 2, name: 'lisi' },
{ id: 1, name: 'zhangsan' },
];
});
</script>
</body>
</html>
运行结果:
相关推荐:
浅谈angularjs中$destory用法
数组filter对数组元素进行过滤的方法
以上就是angularjs使用filter自定义过滤器控制ng-repeat去除重复功能示例的详细内容。