angularjs自定义过滤器

前端之家收集整理的这篇文章主要介绍了angularjs自定义过滤器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

angular.module('myApp',[],function ($filterProvider,$provide,$controllerProvider) {
    $provide.service('Data',function () {
        return [
            {
                name:'张三',age:20,city:'上海'
            },{
                name:'李四',age:30,city:'北京'
            }
        ]
    });
    //创建过滤器第一种方法
    $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;
    })
    //创建过滤器第二种方法
}).filter('filterCity',function () {
    return function (obj) {
        var newObj = [];
        angular.forEach(obj,function (o) {
            if(o.city === '上海'){
                newObj.push(o)
            }
        })
        return newObj;
    }
})
调用

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div ng-app="myApp">
        <div ng-controller="firstController">
            <ul>
                <li ng-repeat="user in data | filterCity">
                    {{user.name}}
                    {{user.age}}
                    {{user.city}}
                </li>
            </ul>
        </div>
    </div>
    <script type="text/javascript" src="../vendor/angular/angularjs.js"></script>
    <script type="text/javascript" src="./app/index.js"></script>
</body>
</html>
原文链接:https://www.f2er.com/angularjs/145956.html

猜你在找的Angularjs相关文章