首页 > 解决方案 > AngularJS - 如何通过 ng-repeat 中的整数数组进行过滤?

问题描述

我有一个 ng-repeat,我用这种方式用一个简单的整数过滤它:

看法:

ng-repeat="t in vm.presencesByPerson | filter: vm.customfilter">

控制器:

在这里,我在下拉列表中有一个观察者,并且基于下拉选择,它传递选择的值以用作过滤器:

this.customfilter = { person: { id: parseInt(filters[0])}};

我这样做是因为presencesByPerson对象的结构是[{person: {id, name, etc..}]

这可以正常工作并被my ng-repeat过滤。

现在,id我不想传递一个 ,而是传递一个id's 数组,如下所示:

arrayID = [x, y, z]

以便它按数组的每个值过滤我的 ng-repeat!

我需要如何修改代码才能使其正常工作?

我想要一个习惯了的类型脚本解决方案语法!谢谢

标签: angularjsfilterangularjs-ng-repeat

解决方案


将您的 customFilter 对象更改为使用arrayID[]

    this.customfilter = function(person) {
        if (arrayID.indexOf(person.id) != -1)
            return true;
    }; 

希望能帮助到你!!

var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {

    $scope.customfilter = function(person) {
        if (arrayID.indexOf(person.id) != -1)
            return true;
    };

    $scope.friends = [{ name: 'John', phone: '555-1276', id: 1 },
        { name: 'Mary', phone: '800-BIG-MARY', id: 2 },
        { name: 'Mike', phone: '555-4321', id: 3 },
        { name: 'Adam', phone: '555-5678', id: 4 },
        { name: 'Julie', phone: '555-8765', id: 5 },
        { name: 'Juliette', phone: '555-5678', id: 6 }
    ]

    arrayID = [1, 3, 6];    
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myShoppingList" ng-controller="myCtrl">
    <label>Search: <input ng-model="searchText"></label>
    <table id="searchTextResults">
        <tr>
            <th>Name</th>
            <th>Phone</th>
        </tr>
        <tr ng-repeat="friend in friends | filter:customfilter">
            <td>{{friend.name}}</td>
            <td>{{friend.phone}}</td>
        </tr>
    </table>
</body>


推荐阅读