AngularJS中有一個filterFilter函數用來對集合過濾,非常方便。源代碼大致如下: function filterFilter(){ return function(aray, expression comparator){ if(!isArray(array)) return arr
AngularJS中有一個filterFilter函數用來對集合過濾,非常方便。
源代碼大致如下:
function filterFilter(){ return function(aray, expression comparator){ if(!isArray(array)) return array; var comparatorType = typeof(comparator), predicates = [], evaluatedObjects = []; predicates.check = function(value){ for(var j = 0; j < predicates.length; jii){ if(!predicates[j](value){ return false; }) } return true; } if(comparatorType != 'function'{ if(comparatorType === 'boolean' && comparator){ comparator = function(obj, text){ return angular.equals(obj, text); } } else { comparator = function(obj, text){ ... } } }) } }
controller部分如下:
angular .module('app') .controller('MainCtrl', ['$scope', function($scope) { $scope.users = $scope.users = [ {name: '', email: '', joined: 2015-1-1} ]; $scope.filter = { fuzzy: '', name: '' }; ... }]);
■ 搜索所有任意欄位
<input type="text" ng-model="filter.any" > <tr ng-repeat="user in users | filter: filter.any"> <td>{{user.name}}</td> <td>{{user.email}}</td> <td>{{user.joined | date}}</td> </tr>
■ 搜索某個欄位
<input type="text" ng-model="filter.name">
<tr ng-repeat="user in users
| filter: filter.any
| filter: {name: filter.name}">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.joined | date}}</td>
</tr>
如果想name欄位完全匹配:
<tr ng-repeat="user in users
| filter: filter.any
| filter: {name: filter.name}:true">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.joined | date}}</td>
</tr>
■ 搜索時間段
contrlller部分修改為:
angular .module('app') .controller('MainCtrl', ['$scope', function($scope) { $scope.users = $scope.users = [ {name: '', email: '', joined: 2015-1-1} ]; $scope.filter = { fuzzy: '', name: '' }; $scope.minDate = new Date('January 1, 2000'); $scope.maxDate = new Date(); $scope.min = function(actual, expected) { return actual >= expected; }; $scope.max = function(actual, expected) { return actual <= expected; }; }]);
頁面部分為:
<input type="text" ng-model="fromDate" data-min-date="{{minDate}}">
<input type="text" ng-model="untilDate" data-max-date="{{maxDate}}">
<tr ng-repeat="user in users
| filter: filter.any
| filter: {name: filter.name}
| filter: {joined: untilDate}:max
| filter: {joined: beforeDate}:min">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.joined | date}}</td>
</tr>