在控制器或服務中使用過濾器
通過注入 $filter
,Angular 模組中的任何已定義過濾器都可以用於控制器,服務,指令甚至其他過濾器。
angular.module("app")
.service("users", usersService)
.controller("UsersController", UsersController);
function usersService () {
this.getAll = function () {
return [{
id: 1,
username: "john"
}, {
id: 2,
username: "will"
}, {
id: 3,
username: "jack"
}];
};
}
function UsersController ($filter, users) {
var orderByFilter = $filter("orderBy");
this.users = orderByFilter(users.getAll(), "username");
// Now the users are ordered by their usernames: jack, john, will
this.users = orderByFilter(users.getAll(), "username", true);
// Now the users are ordered by their usernames, in reverse order: will, john, jack
}