html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <div ng-app="myApp"> <div ng-controller="firstController"> <ul> <!--这里用到了自定义的过滤器filterAge--> <li ng-repeat="user in data | filterAge"> {{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> <script> </script> </body> </html>
js:
angular.module('myApp', [], function ($filterProvider, $provide, $controllerProvider) { //注册service $provide.service('Data', function () { return [ { name: "张三1", age: 21, city: "北京" }, { name: "张三2", age: 22, city: "北京" }, { name: "张三3", age: 23, city: "上海" }, { name: "张三4", age: 24, city: "北京" }, ]; }); //注册filter $filterProvider.register('filterAge', function () { return function (obj) { var newObj = []; angular.forEach(obj,function (o) { //过滤出年龄大于22岁的 if(o.age>22){ newObj.push(o); } }); return newObj; }; }); //注册controller $controllerProvider.register('firstController', function ($scope, Data) { $scope.data = Data; }); });
运行结果:
补充:传多个参数的过滤器
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义过滤器复习</title> <script type="text/javascript" src="../../vendor/angular/angularJs.js"></script> </head> <body ng-app="app"> <div> <!--过滤器的参数就是前面穿进去的参数--> <h1>{{ true | checkmark }}</h1> <h1>{{ false | checkmark }}</h1> <input type="text" placeholder="请输入你的体重" ng-model="yourWeight"> <h2>体重:{{yourWeight}}kg</h2> <!--过滤器如果要传入第二个参数就在过滤器后面加一个:--> <h2>评测:{{yourWeight|weightFilter:"张三"}}</h2> </div> <script> angular.module('app', []) .filter('checkmark', function () { return function (input) { return input ? 'u2713' : 'u2718'; } }) .filter('weightFilter', function () { return function (input,inputTwo) { if (input < 50) { return inputTwo + "偏瘦"; } else if (input >= 100) { return inputTwo + "偏胖"; } else { return inputTwo + "正常"; } } }) </script> </body> </html>
执行结果: