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


95

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

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

我想添加一个自定义过滤器,以使其年龄基于两个输入值min_agemax_age(在年龄之间)进行过滤。

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

我对AngularJS非常了解:(

我尝试过但不起作用的小提琴在这里http://jsfiddle.net/ed9A2/20/

我的无效代码的副本粘贴在这里

视图

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

Answers:


197

试试这个:

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

7

希望下面这个链接的答案会有所帮助, 多值过滤器

并以示例来研究小提琴

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

小提琴


如果在列表中找不到搜索到的属性,此函数将返回所有结果,如果该值不存在于列表中,该如何反转这种行为并不返回任何结果?
Zakaria Belghiti

0

检视档案(HTML或EJS)

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

和在控制器

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.