AngularJS多重过滤器,具有自定义过滤功能

时间:2013-09-13 17:30:44

标签: javascript angularjs angularjs-ng-repeat

我正在尝试使用多个过滤器+使用自定义过滤器功能过滤列表。

最初的工作jsfiddle示例是http://jsfiddle.net/ed9A2/1/,但现在我想改变年龄过滤方式。

我想添加一个自定义过滤器,以便年龄根据两个输入值进行过滤,即 min_age max_age ,(年龄之间) )。

在研究doc之后。我发现人们有类似的问题,用户Mark Rajcok回答http://docs.angularjs.org/api/ng.filter:filter#comment-648569667看起来很好,应该可以工作。但我有问题将其应用到我的代码中,这主要是因为我有其他多个过滤器。

我对AngularJS很新:(

我在这里尝试过而且不工作的小提琴http://jsfiddle.net/ed9A2/20/

我的NOT工作代码的复制粘贴在这里

查看

<div ng-app ng-controller="MainController">
<table class="fancyTable">
    <tr>
        <th>Player id</th>
        <th>Player name</th>
        <th>Age</th>
    </tr>
    <tr>
        <td><input ng-model="player_id" /></td>
        <td><input ng-model="player_name" /></td>
        <td>
            Min Age:<input ng-model="min_age" />
            Max Age:<input ng-model="max_age" />
        </td>
    </tr>
    <tr ng-repeat="player in players | filter:{id: player_id, name:player_name, age:ageFilter}">
        <td>{{player.id}}</td>
        <td>{{player.name}}</td>
        <td>{{player.age}}</td>
    </tr>
</table>

控制器

function MainController($scope) {

$scope.player_id = "";
$scope.player_name = "";
$scope.player_age = "";
$scope.min_age = 0;
$scope.max_age = 999999999;

$scope.ageFilter = function(player) {
    return ( player > $scope.min_age && player.age < $scope.max_age);
}

$scope.players = [
        {"name": "Rod Laver",
            "id": "rod",
            "date": "1938/8/9",
            "imageUrl": "img/rod-laver.gif",
            "age": 75},
        {"name": "Boris Becker", 
            "id": "borix",
            "date": "1967/11/22",
            "imageUrl": "img/boris-becker.gif",
            "age": 45},
        {"name": "John McEnroe",
            "id": "mcenroe",
            "date": "1959/2/16",
            "imageUrl": "img/john-mc-enroe.gif",
            "age": 54},
        {"name": "Rafa Nadal",
            "id": "nadal",
            "date": "1986/5/24",
            "imageUrl": "img/ndl.jpg",
            "age": 27}
    ]
}

3 个答案:

答案 0 :(得分:192)

试试这个:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

答案 1 :(得分:7)

希望以下链接中的答案会有所帮助, Multiple Value Filter

通过示例

来看看小提琴
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

fiddle

答案 2 :(得分:0)

查看文件(HTML或EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

并在控制器中

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}