3

我想实现以下理论代码:

VIEW.html

<li ng-repeat="player in players | filter:myCustomFilter(player)">{{player.name}}

控制器.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())?

4

3 回答 3

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;
    }
}

结果

于 2013-06-15T02:16:13.113 回答
2

您不需要将播放器传递给过滤器

<li ng-repeat="player in players | filter:myCustomFilter">{{player.name}}

应该管用

于 2013-06-15T00:54:17.903 回答
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;
    }
  } 

}

签出一个工作的 jsfiddle

于 2017-04-06T20:37:25.903 回答