我想要实现以下理论代码:
VIEW.html
<li ng-repeat="player in players | filter:myCustomFilter(player)">{{player.name}}
CONTROLLER.js
// some theoretical conditional statement that return a boolean
$scope.otherCondition = true;
$scope.myCustomFilter = function(player) {
return player.name.substring(0,1).match(/A/gi) && $scope.otherCondition;
}
所以我希望所有玩家都加载到Angular模型中,但我只想将玩家渲染到名称以字母“A”开头的DOM中。当我尝试做这样的事情时,我的控制台告诉我player
未定义。我是否需要编写自定义过滤器才能实现此目的(通过angular.module().filter()
)?
答案 0 :(得分:7)
这是一个工作小提琴:http://jsfiddle.net/orlenko/jV6DK/
Html代码(正如Karl Zilles建议的那样):
<div ng-app>
<div ng-controller="MyController">
<h2>Names starting with "A":</h2>
<ul>
<li ng-repeat="player in players | filter:myCustomFilter">{{player.name}}</li>
</ul>
<h2>All Names:</h2>
<ul>
<li ng-repeat="player in players">{{player.name}}</li>
</ul>
</div>
</div>
使用Javascript:
function MyController($scope) {
$scope.players = [{
name: 'Arthur'
}, {
name: 'William'
}, {
name: 'Bertha'
}, {
name: 'Alice'
}];
$scope.otherCondition = true;
$scope.myCustomFilter = function(player) {
return player.name.substring(0,1).match(/A/gi) && $scope.otherCondition;
}
}
答案 1 :(得分:2)
您无需将播放器传递给过滤器
<li ng-repeat="player in players | filter:myCustomFilter">{{player.name}}
应该工作
答案 2 :(得分:0)
给出的答案只是部分正确,如果您需要将更多参数传递给函数,您需要创建一个闭包并将这些参数传递给闭包,如下所示:
'A'
传递给闭包,player
作为上下文的一部分传递。
HTML:
<div ng-app>
<div ng-controller="MyController">
<h2>Names starting with "A":</h2>
<ul>
<li ng-repeat="player in players | filter:myCustomFilter('A')">{{player.name}}</li>
</ul>
<h2>All Names:</h2>
<ul>
<li ng-repeat="player in players">{{player.name}}</li>
</ul>
</div>
</div>
JS:
function MyController($scope) {
$scope.players = [{
name: 'Arthur'
}, {
name: 'William'
}, {
name: 'Bertha'
}, {
name: 'Alice'
}];
$scope.otherCondition = true;
$scope.myCustomFilter = function(letter) {
return function(player) {
var rgxp = new RegExp(letter, "g");
return player.name.substring(0, 1).match(rgxp) && $scope.otherCondition;
}
}
}