如果我们使用带有 ngRepeat 指令的 AngularJs 列表并在其上设置过滤器,我们可能想知道过滤后有多少项。
我们可以通过两种方式执行此操作,在模板中和使用 javascript(控制器)。
如何在模板中获取过滤器计数
让我们考虑例子
例子
<!DOCTYPE html> <html> <head> <title>www.onitroad.com</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> </head> <body data-ng-app="MyModule" data-ng-controller="MyController"> <select data-ng-model="filterGender"> <option value='male'>Male</option> <option value='female'>Female</option> </select> <ul> <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li> </ul> <h3>{{ usersList.length | number }}/{{ users.length }}</h3> <script> angular.module('MyModule', []) .controller('MyController', function($scope){ $scope.users = [ {name: 'Mike', gender: 'male', age: 23}, {name: 'Jenifer', gender: 'female', age: 32}, {name: 'Tom', gender: 'male', age: 14}, {name: 'Ellen', gender: 'female', age: 42}, {name: 'John', gender: 'male', age: 22}, {name: 'Hayk', gender: 'male', age: 18}, {name: 'Eliana', gender: 'female', age: 28} ]; }) .filter('gender', function(){ return function(users, gender){ if(!gender){ return users; } var arr = []; angular.forEach(users, function(v){ if(v.gender === gender){ arr.push(v); } }) return arr; } }) </script> </body> </html>
如我们所见,我们可以将过滤结果收集到另一个变量中,然后使用该数组(获取其长度)。
“users”数组不变,表示“users”数组包含所有用户,“usersList”数组包含过滤后剩余的用户。
现在让我们尝试在控制器内部解决它。
如何在控制器中获取过滤器计数
<!DOCTYPE html> <html> <head> <title>www.onitroad.com</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> </head> <body data-ng-app="MyModule" data-ng-controller="MyController"> <select data-ng-model="filterGender" ng-change="onGenderChange()"> <option value='male'>Male</option> <option value='female'>Female</option> </select> <ul> <li data-ng-repeat="user in usersList" data-ng-bind="user.name"></li> </ul> <h3>{{ usersList.length | number }}/{{ users.length }}</h3> <script> angular.module('MyModule', []) .controller('MyController', function($scope, $filter){ $scope.users = [ {name: 'Mike', gender: 'male', age: 23}, {name: 'Jenifer', gender: 'female', age: 32}, {name: 'Tom', gender: 'male', age: 14}, {name: 'Ellen', gender: 'female', age: 42}, {name: 'John', gender: 'male', age: 22}, {name: 'Hayk', gender: 'male', age: 18}, {name: 'Eliana', gender: 'female', age: 28} ]; $scope.usersList = angular.copy($scope.users); $scope.onGenderChange = function(){ $scope.usersList = $filter('gender')($scope.users, $scope.filterGender) }; }) .filter('gender', function(){ return function(users, gender){ if(!gender){ return users; } var arr = []; angular.forEach(users, function(v){ if(v.gender === gender){ arr.push(v); } }) return arr; } }) </script> </body> </html>
日期:2020-06-02 22:18:46 来源:oir作者:oir