您可以color:'blue'
使用 format 中的任何表达式进行自定义,因此只要定义了过滤器并存在于当前范围内,类似的filter:expression
东西color:myColor
就可以正常工作。color
myColor
在您的控制器中,您可以执行相同的操作。
$scope.filteredArr = $filter('color')($scope.arr,myColor);
这是一个基于您的 jsFiddle 示例的示例。
Javascript:
angular.module('app', [])
.filter('eyecolor', function () {
return function ( people, color ) {
var arr = [];
for ( var i = people.length; i--; ) {
if ( people[i].eyeColor === color ) {
arr.push( people[i] );
}
}
return arr;
}
})
.controller('ctrl', function ($scope, $filter) {
$scope.desiredColor = 'Brown';
$scope.people = [
{
name: 'Bob',
eyeColor: 'Brown'
}, {
name: 'Katherine',
eyeColor: 'Yellow'
}, {
name: 'Chun',
eyeColor: 'Black'
}
];
$scope.peopleFilter = $filter('eyecolor')( $scope.people, $scope.desiredColor );
});
html:
<div ng-app="app">
<div ng-controller="ctrl">Color Desired:
<input ng-model="desiredColor" /><br/>
<div ng-repeat="person in people | eyecolor: desiredColor">
HTML filter: {{person.name}} has eye color {{person.eyeColor}}</div>
<div ng-repeat="person in peopleFilter">
Controller filter: {{ person.name }} has eye color {{ person.eyeColor }}</div>
</div>
</div>