自定义过滤器

两种方式

  • module.filter(name, filterFactory)

  • @$filterProvider.register().

例子: index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<div ng-app="myApp">

    <div ng-controller="firstController">
        <p>filterAge:</p>
        <ul>
            <li ng-repeat="user in data | filterAge">
                {{user.name}}
                {{user.age}}
                {{user.city}}
            </li>
        </ul>
        <p>filterCity:</p>
        <ul>
            <li ng-repeat="user in data | filterCity">
                {{user.name}}
                {{user.age}}
                {{user.city}}
            </li>
        </ul>
    </div>
</div>


<script src="//cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
<script type="text/javascript" src="app/index.js"></script>


</body>
</html>

app/index.js

var myApp = angular.module('myApp', [], function ($filterProvider, $provide, $controllerProvider) {

    $provide.service('Data', function () {
        return [
            {
                name: '张三',
                age: '20',
                city: '上海'
            },
            {
                name: '李四',
                age: '30',
                city: '北京'
            }
        ];

    });
    //$filterProvider.register方式
    $filterProvider.register('filterAge', function () {
        return function (obj) {
            var newObj = [];

            angular.forEach(obj, function (o) {
                if (o.age > 20) {
                    newObj.push(o);
                }
            });

            return newObj;

        }
    });


    $controllerProvider.register('firstController', function ($scope, Data) {
        $scope.data = Data;
    })
})

// module.filter方式
.filter('filterCity',function(){
    return function(obj){
        var newObj = [];

        angular.forEach(obj, function (o) {
            if (o.city === '上海') {
                newObj.push(o);
            }
        });

        return newObj;
    }
})

效果:

Last updated