欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Angularjs中如何使用filterFilter函数过滤

程序员文章站 2023-02-19 11:22:10
angularjs的filter,中文名“过滤器”是用来过滤变量的值,或者格式化输出,得到自己所期望的结果或格式的东东。angularjs中有一个filterfilter函...

angularjs的filter,中文名“过滤器”是用来过滤变量的值,或者格式化输出,得到自己所期望的结果或格式的东东。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>

以上所述是小编给大家分享的angularjs中如何使用filterfilter函数过滤的相关知识,希望对大家有所帮助。