简体   繁体   English

数组的角度过滤器数组

[英]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. 在过去的几天里,我遇到了使用Angular过滤数组数组并显示它的困难。 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: Search1()函数正常工作:

$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 Search2()函数不会改变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? 任何人都可以在Search2()函数中给出提示可能出错的提示吗? While I am logging filteredItems, it logs me correct amount of answers, but the list still remains of the same size as it was. 当我正在记录filteredItems时,它会记录正确数量的答案,但列表仍然保持与原来相同的大小。 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. 正如@mgilson所指出的那样,你需要从过滤器回调函数中返回一个布尔值,但是你将返回一个总是很简单的数组。 There is also no need to use $filter('filter') here. 这里也没有必要使用$filter('filter') 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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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