Search code examples
javascriptangularjsangular-filters

Angular filter by multiple strings in array


The issue is that filtering for items with 2 categories does not return anything. So by filtering for 'mulder' an item with the categories "mulder" and "scully" should be returned

I have data which defines the following:

$scope.allnodes = [
{ name: "This is node 1", category: ["mulder"] },
{ name: "Another title is this one", category: ["scully"] },
{ name: "This is Another title", category: ["mulder"] },
{ name: "And finally a fourth title", category:  ["mulder","scully"] }      
];

The relevant app js is:

$scope.categories = ['Mulder','Scully'];
$scope.filterByCategory = function (node) {
    return $scope.filter[node.category] || noFilter($scope.filter);
};


function noFilter(filterObj) {
    for (var key in filterObj) {
        if (filterObj[key]) {
            return false;
            }
        }
    return true;
}  

This is the partial rendering:

<div ng-controller="myCtrl">
    <b>Category:</b>
    <div ng-repeat="cat in categories">
        <b><input type="checkbox" ng-model="filter[cat]" />{{cat}} 
        </b>
    </div>
    <hr />
    <div ng-repeat="node in filtered=(allnodes | filter:filterByCategory)">
    {{node.title}} 
        <div ng-repeat="term in node.category">
            <label class="label label-info">{{term}}</label>
        </div> 
    </div>
    <hr />
    Number of results: {{filtered.length}}
</div>

http://jsfiddle.net/kevinhowbrook/h2bekshb/6/


Solution

  • The problem is that node.category is an array.

    Your filterByCategory should look something like this:

    $scope.filterByCategory = function(node) {
        for (var key in $scope.filter) {
          if ($scope.filter[key] && (!node.category || node.category.indexOf(key) < 0)) {
            return false;
          }
        }
    
        return true;
    };
    

    This function checks that the categories of the current item contain all of the selected categories in the filter.

    http://jsfiddle.net/cutm3p9c/1/