数组的角度过滤器数组

时间:2016-03-14 13:30:10

标签: javascript arrays angularjs filter

在过去的几天里,我遇到了使用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时,它会记录正确数量的答案,但列表仍然保持与原来相同的大小。 我在这里缺少自定义过滤器的主要逻辑是什么?

谢谢,

1 个答案:

答案 0 :(得分:0)

正如@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;
});
相关问题