AngularJs Filter自定义过滤器控制ng-repeat去除重复

前端之家收集整理的这篇文章主要介绍了AngularJs Filter自定义过滤器控制ng-repeat去除重复前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码

<div ng-app="myApp" ng-controller="myCtrl">
    <p ng-repeat="x in items | unique:'id'">
        {{x.id}}---{{x.name}}
    </p>
</div>
<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,];
    });
</script>
结果:

原文链接:https://www.f2er.com/angularjs/149399.html

猜你在找的Angularjs相关文章