由数组中的多个字符串进行角度过滤

时间:2016-02-01 21:57:19

标签: javascript angularjs angular-filters

问题是对具有2个类别的项目进行过滤不会返回任何内容。因此,通过过滤“mulder”,应该返回带有“mulder”和“scully”类别的项目

我有定义以下内容的数据:

$scope.allnodes = [
{ name: "This is node 1", category: ["mulder"] },
{ name: "Another title is this one", category: ["scully"] },
{ name: "This is Another title", category: ["mulder"] },
{ name: "And finally a fourth title", category:  ["mulder","scully"] }      
];

相关应用程序js是:

$scope.categories = ['Mulder','Scully'];
$scope.filterByCategory = function (node) {
    return $scope.filter[node.category] || noFilter($scope.filter);
};


function noFilter(filterObj) {
    for (var key in filterObj) {
        if (filterObj[key]) {
            return false;
            }
        }
    return true;
}  

这是部分渲染:

<div ng-controller="myCtrl">
    <b>Category:</b>
    <div ng-repeat="cat in categories">
        <b><input type="checkbox" ng-model="filter[cat]" />{{cat}} 
        </b>
    </div>
    <hr />
    <div ng-repeat="node in filtered=(allnodes | filter:filterByCategory)">
    {{node.title}} 
        <div ng-repeat="term in node.category">
            <label class="label label-info">{{term}}</label>
        </div> 
    </div>
    <hr />
    Number of results: {{filtered.length}}
</div>

http://jsfiddle.net/kevinhowbrook/h2bekshb/6/

1 个答案:

答案 0 :(得分:0)

问题是node.category是一个数组。

您的filterByCategory应如下所示:

$scope.filterByCategory = function(node) {
    for (var key in $scope.filter) {
      if ($scope.filter[key] && (!node.category || node.category.indexOf(key) < 0)) {
        return false;
      }
    }

    return true;
};

此功能检查当前项目的类别是否包含过滤器中的所有选定类别。

http://jsfiddle.net/cutm3p9c/1/