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

izj3ouym  于 2022-12-28  发布在  Java
关注(0)|答案(3)|浏览(135)

我正在尝试用多个过滤器+一个自定义过滤器函数来过滤列表。
最初的jsfiddle示例是http://jsfiddle.net/ed9A2/1/,但现在我想更改过滤年龄的方式。
我想添加一个自定义过滤器,以便年龄根据两个输入值进行过滤,这两个输入值是min_agemax_age(介于年龄之间)。
在查看了doc之后,我发现人们有类似的问题,用户Mark Rajcok回答http://docs.angularjs.org/api/ng.filter:filter#comment-648569667看起来不错,应该可以工作。但是我在将它应用到我的代码中时遇到了问题,这主要是因为我有其他多个过滤器。
我的尝试和不工作的小提琴在这里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}
    ]
}
fcg9iug3

fcg9iug31#

试试这个:

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

axzmvihb2#

希望下面的答案在此链接将有所帮助,多值过滤器
我们来看一下这个例子

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

fiddle

muk1a3rh

muk1a3rh3#

在视图文件(HTML或EJS)中

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

和控制器中

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

相关问题