angularJS 自定义过滤器
创建自定义过滤器非常容易。创建自定义过滤器需要将它放到自己的模块中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div ng-app="myApp">
<div ng-controller="firstController">
<ul>
<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>
</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('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;
}
})