使用 Angular 中的复选框过滤 json 文件

Filter json file with tickboxes in Angular

我正在尝试从我的 JSON 文件中过滤结果,以便用户可以点击女士或男士 'styles',但有些产品同时具有女士和男士款式,所以我怎么会能够在没有三个勾选框的情况下显示 'both' 的结果?我知道我的 JSON 中不能有重复的名称,但现在这样做只是为了举例。任何帮助,将不胜感激。我把我的代码放在这里:

http://plnkr.co/edit/fXOZHqo48ntvsdJA875y?p=preview

<div ng-controller="myCtrl">
    <div ng-repeat="(prop, ignoredValue) in { 'category': true, 'cut': true }" ng-init="filter[prop]={}">
        <b>{{prop | capitalizeFirst}}:</b><br />
        <span class="quarter" ng-repeat="opt in getOptionsFor(prop)">
            <b><input type="checkbox" ng-model="filter[prop][opt]" />&nbsp;{{opt}}</b>
        </span>
        <hr />
    </div>
    <div ng-repeat="w in filtered=(products | filter:filterByProperties)">
        {{w.name}} ({{w.category}})
    </div>
    <hr />
    Number of results: {{filtered.length}}
</div>

您需要对 json 进行一些更改。

  1. 只要 cut 有一个值,那么它就是 string & 只要有多个值,那么你可以维护一个 array"cut": "ladies""cut": "mens","cut": ["ladies","mens"]
  2. 您需要在 filterByProperties 函数中处理字符串和过滤内容

标记

<span ng-show="!isArray(opt)" class="quarter" ng-repeat="opt in getOptionsFor(prop)">
    <b><input type="checkbox" ng-model="filter[prop][opt]" />&nbsp;{{opt}}</b>
</span>

代码

$scope.isArray = function(val) {
    return angular.isArray(val)
}

$scope.filterByProperties = function(product) {
    // Use this snippet for matching with AND
    var matchesAND = true;
    for (var prop in $scope.filter) {
      if (noSubFilter($scope.filter[prop])) continue;
      if (!$scope.isArray(product[prop])) { //if its not an array
        if (!$scope.filter[prop][product[prop]]) {
          matchesAND = false;
          break;
        }
      } else {
        //if its an array
        for (var i = 0; i < product[prop].length; i++) {
          var anyPropMatch = false;
          if ($scope.filter[prop][product[prop][i]]) {
            anyPropMatch = true;
            break;
          }
        }
        if (!anyPropMatch) {
          matchesAND = false;
          break;
        }
      }
    }
    return matchesAND;
};

Working Plunkr