【问题标题】:How to filter an array of objects based on an array of a specific object propert?如何根据特定对象属性的数组过滤对象数组?
【发布时间】:2017-05-25 04:21:15
【问题描述】:

这是我使用ng-repeat的html的一个小例子:

<div ng-repeat="item in vm.templateList | filter: vm.myFilter">
   <h3>{{item.Code}}</h3>
</div>

在Js文件中vm.templateList如下(举例):

vm.templateList = [{Code: 'a', ID: 1}, 
                   {code: 'a', ID: 2},
                   {code: 'b', ID: 3},
                   {code: 'c', ID: 4}];

想象一下,我想为所有 ID 为 1 的项目和 ID 为 2 的项目过滤此列表。

我原来的做法是这样的:

vm.filter = {ID: 1};

但这是我只能过滤 1 个 ID 的列表。谁能推荐一个方法?

【问题讨论】:

标签: angularjs angularjs-ng-repeat angularjs-filter


【解决方案1】:

您可以将以下 AngularJS 过滤器添加到您的应用程序中:

// add a custom filter to your module
angular.module('MyModule').filter('myFilter', function() {
    // the filter takes an additional input filterIDs
    return function(inputArray, filterIDs) {
        // filter your original array to return only the objects that
        // have their ID in the filterIDs array
        return inputArray.filter(function (entry) {
            return this.indexOf(entry.ID) !== -1;
        }, filterIDs); // filterIDs here is what "this" is referencing in the line above
    };
});

然后你在控制器中声明你的过滤器数组:

vm.IDs = [1, 2];

那么你的视图应该是这样的:

<div ng-repeat="item in vm.templateList | myFilter: vm.IDs">
    <h3>{{item.Code}}</h3>
</div>

【讨论】:

    【解决方案2】:

    你可以使用类似的东西:

    html:

    <section>
        <div ng-repeat="item in vm.templateList | filter:checkFilterOptions">
           <h3>{{item.Code}}</h3>
        </div>
    </section>
    

    Js:

        $scope.vm = {};
        $scope.vm.templateList = [
                        {Code: 'a', ID: 1},
                        {Code: 'a', ID: 2},
                        {Code: 'b', ID: 3},
                        {Code: 'c', ID: 4}
                        ];
    
        $scope.filterOptions = [1,2,3];
    
        $scope.checkFilterOptions = function(value, index) {
          return value.ID && $scope.filterOptions.indexOf(value.ID) !== -1;
        }
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2021-04-15
      • 2018-07-06
      • 2020-02-29
      • 1970-01-01
      相关资源
      最近更新 更多