简体   繁体   中英

Angular filter array of an array

For the past few days I have had difficulties with filtering an array of array with Angular and displaying it. I have tried searching for similar posts but I could not find solution for my case.

Example how my data looks:

$scope.answers = [
    {title: "Qestion1", keywords: ["dino", "dog", "cat"]},
    {title: "Quessstion2", keywords: ["cat", "dog"]}
];

Currently I am displaying a list:

<div class="solution-box" ng-repeat="answer in pagedItems[currentPage]">

I have two search fields:

<input type="text" ng-model="title"  ng-change="search1()"  class="form-control" placeholder="Filter by title">
<input type="text" ng-model="keys"  ng-change="search2()" class="form-control" placeholder="Filter by keywords">

Search1() function which just works fine:

$scope.search1 = function () {
     $scope.filteredItems = $filter('filter')($scope.answers, function (answer) {
         if (searchMatch(answer.title, $scope.title))
             return true;
         return false;
     });
     $scope.currentPage = 0;
     // now group by pages
     $scope.groupToPages();
 };

Search2() function which does not alter filteredItems

$scope.search2 = function () {
        $scope.filteredItems = $filter('filter')($scope.answers, function (answer) {
            return $filter('filter')(answer.keywords, function (keyword) {
                if (searchMatch(keyword, $scope.keys)) {
                    console.log($scope.filteredItems + '/' + keyword + '|' + $scope.keys);
                    return true;
                }
                return false;
            });
        });
        $scope.currentPage = 0;
        // now group by pages
        $scope.groupToPages();
    };

Could anyone please give tips what could be wrong in Search2() function? While I am logging filteredItems, it logs me correct amount of answers, but the list still remains of the same size as it was. What is the main logic of custom filters that I am missing here?

Thanks,

As @mgilson pointed out you need to return a boolean from the filter callback function but you are returning an array which will always be truthy. There is also no need to use $filter('filter') here. You could just do something like this:

$scope.filteredItems = $scope.answers.filter(function(answer) {
    var matches = answer.keywords.filter(function() {
        return searchMatch(keyword, $scope.keys);
    });
    return matches.length > 0;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM