1

I'm struggling to find a way of filtering a set of results in an ng-repeat, based on an array of numbers. The numbers can represent results I want to see, or not see. I'm able to use a filter in the view and filter by one number, which works, but I want to put an array there and filter by the array. I don't care if the filter is in the view, the controller, or a separate filter.

The code below successfully filters topics with the forum id of 60

  <div ng-repeat="topic in topics | filter:{forum_id:60}">
    Forum ID: {{topic.forum_id}} Forum Name: {{topic.forum_title}}
  </div>

I want to filter by an array

  <div ng-repeat="topic in topics | filter:{forum_id:ARRAY_HERE}">
    Forum ID: {{topic.forum_id}} Forum Name: {{topic.forum_title}}
  </div>

Full plunk here: https://plnkr.co/edit/dCZ7DV?p=preview

isherwood
  • 58,414
  • 16
  • 114
  • 157
mediaguru
  • 1,807
  • 18
  • 24
  • 1
    Please include all relevant code in a [mcve] in the question itself. Don't just post a link to the code that shows the issue, as many people are behind firewalls that disallow navigation to code sharing sites. You can replicate a lot of web functionality using Stack Snippets. – Heretic Monkey Aug 18 '17 at 18:11

3 Answers3

1

Pass your own function to filter:

<div ng-repeat="topic in topics | filter:myFilterMethod(topic)">
    Forum ID: {{topic.forum_id}} Forum Name: {{topic.forum_title}}
</div>

and in your controller:

$scope.myFilterMethod = function() {
    return function(e) {
        return $scope.filterBy.includes(e.forum_id);
    }
}

updated plunkr

baao
  • 71,625
  • 17
  • 143
  • 203
1

Also you can use ng-if and indexOf function for this.

 <div ng-repeat="topic in topics" ng-if="filterBy.indexOf(topic.forum_id) !== -1">
     Forum ID: {{topic.forum_id}} Forum Name: {{topic.forum_title}}
 </div>

Demo

Hadi J
  • 16,989
  • 4
  • 36
  • 62
1

natively, the filter property in angular doesn't work that way, so you need to define a manual filter by yourself.

You can do it like this answer

angular.module('myApp').filter('selectedArray', function() {
    return function(array, tags) {
        return array.filter(function(object) {

            for (var i in object.XXX) {
                if (array.indexOf(object.XXX[i]) != -1) {
                    return true;
                }
            }
            return false;

        });
    };
});

and then you can use it like :

<ul>
    <li ng-repeat="task in tasks | selectedArray:Array"></li>
</ul>

In this example as the response is a array of objects, you need to tailor it to your array,

Hope it helps.