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: '' }; ... }]);
■ 搜索所有任意字段
{ {user.name}} { {user.email}} { {user.joined | date}}
■ 搜索某个字段
{ {user.name}} { {user.email}} { {user.joined | date}}
如果想name字段完全匹配:
{ {user.name}} { {user.email}} { {user.joined | date}}
■ 搜索时间段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; }; }]);
页面部分为:
{ {user.name}} { {user.email}} { {user.joined | date}}