繁体   English   中英

数组的角度过滤器数组

[英]Angular filter array of an array

在过去的几天里,我遇到了使用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">

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

任何人都可以在Search2()函数中给出提示可能出错的提示吗? 当我正在记录filteredItems时,它会记录正确数量的答案,但列表仍然保持与原来相同的大小。 我在这里缺少自定义过滤器的主要逻辑是什么?

谢谢,

正如@mgilson所指出的那样,你需要从过滤器回调函数中返回一个布尔值,但是你将返回一个总是很简单的数组。 这里也没有必要使用$filter('filter') 你可以这样做:

$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