2016-03-14 239 views
3

在过去的几天里,我用Angular过滤了一个数组数组并且显示它有困难。我试过寻找类似的帖子,但我找不到解决方案。阵列的角度滤波器阵列

比如我的数据的外观:

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

目前我显示列表:

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

我有两个搜索字段:

<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"> 

搜索1()函数,它只是正常工作:

不改变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(); 
    }; 

任何人都可以请给小费什么可以在搜索2()函数是错误

搜索2()函数? 虽然我正在记录filteredItems,但它会记录正确数量的答案,但该列表仍然保持与原来相同的大小。 我在这里失踪的自定义过滤器的主要逻辑是什么?

感谢,

+1

我建议做一个jsfiddle/plunker。 – jusopi

+1

'$ filter('filter')'会返回你传给它的函数返回一个真值。使用'search2',你返回另一个'$ filter('filter')'的结果,这可能是一个数组,因此不会进行过滤。你期望内部过滤器在那里做什么? – mgilson

+0

我认为$ filter('filter')在数组的一个级别上工作,所以对于内部过滤器,我想过滤关键字,然后用过滤的关键字过滤答案。这个想法是通过过滤标题和关键字来显示列表。 –

回答

0

由于@mgilson指出,需要从过滤器回调函数返回一个布尔值,但你返回一个数组,这将永远是truthy。这里也没有必要使用$filter('filter')。你可以这样做:

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

非常感谢! –