This article uses three different ways to customize an array filter.
Array list:
[
{name: ' John ', Age:20, City: ' Shanghai '},
{name: ' li si ', age:30, City: ' Beijing '},
{name: ' Harry ', age:25, City: ' Shenzhen '}
]
1. Custom Filter Mode One (define a method within the Controller method)
Html:
<li ng-repeat= "Item in List | Filter:myfilter1 ">
Js:
var app=angular.module (' myApp ', []);
App.controller ("Myctrl", Function ($scope, List) {
$scope. list=list;
Custom Filter Mode One displays only persons younger than 30 years of age
$scope. Myfilter1=function (obj) {
if (Obj.age <) {return
true;
} return false;};
2. Custom Filter Mode two (. Filter method)
Html:
<li ng-repeat= "Item in List | Filtercity ">
Js:
Custom filter mode Two does not show Shanghai's personnel
app.filter (' filtercity ', function () {return
function (obj) {
var Newobj=[];
Angular.foreach (Obj,function (o) {
if (o.city!= "Shanghai") {
newobj.push (o);
}
});
return newObj;
}
});
Html:
<li ng-repeat= "Item in List | Myfilterage ">
Js:
Angular.module (' myApp ', [],function ($filterProvider, $provide, $controllerProvider) {
//Custom filter mode three Displays only people older than 25 years old
$filterProvider. Register (' Myfilterage ', function () {return
function (obj) {
var newobj= [];
Angular.foreach (Obj,function (o) {
if (o.age >=) {
newobj.push (o);
}
);
return newObj;
}
});
Define services
$provide. Service (' List ', function () {return
[
{name: ' John ', Age:20, City: ' Shanghai '},
{name: ' Li Si ', age:30, City: ' Beijing '},
{name: ' Harry ', age:25, City: ' Shenzhen '}
]
};
Defines
the controller $controllerProvider. Register (' Myctrl ', function ($scope, List) {
$scope. list=list;
}
);