我有这个控制器:
angular.module('myApp', [])
.controller('testCtrl', ['$scope', '$filter',
function($scope, $filter) {
$scope.users = [{
name: "Hanna",
gender: "female"
}, {
name: "Martin",
gender: "male"
}, {
name: "Kim",
gender: "transgender"
}];
$scope.traditionalUsers = $filter('filter')($scope.users,femaleOrMale());
function femaleOrMale(user) {
return ['female','male'].indexOf(user.gender);
}
}
]);
我想过滤具有与数组匹配的属性的用户。这不起作用。见plunk。如何正确调用过滤器?
答案 0 :(得分:2)
删除()
当您在
中编写femaleOrMale
时,您在没有任何参数的情况下调用femaleOrMale()
函数
$scope.traditionalUsers = $filter('filter')($scope.users, femaleOrMale());
您编写的将函数本身传递给过滤器的内容是
$scope.traditionalUsers = $filter('filter')($scope.users, femaleOrMale);
这将使页面不再出现错误,但它不会显示male
和female
作为传统用户,我怀疑这是你想要的。您需要从femaleOrMale
过滤器返回一个布尔值,indexOf
返回匹配的索引,如果没有匹配则返回-1
,因此请比较-1
。< / p>
return ['female','male'].indexOf(user.gender) != -1;
angular.module('myApp', [])
.controller('testCtrl', ['$scope', '$filter',
function($scope, $filter) {
$scope.users = [{
name: "Hanna",
gender: "female"
}, {
name: "Martin",
gender: "male"
}, {
name: "Kim",
gender: "transgender"
}];
$scope.traditionalUsers = $filter('filter')($scope.users, femaleOrMale);
function femaleOrMale(user) {
return ['female','male'].indexOf(user.gender) != -1;
}
}
]);
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-app='myApp'>
<div ng-controller='testCtrl'>
<h3>Male and female users:</h3>
{{traditionalUsers}}
</div>
</div>
</body>
</html>
&#13;