使用带有硬编码复选框的angularjs中的过滤器

时间:2013-07-11 11:50:42

标签: angularjs filtering

我有一个复选框列表,我想用它来过滤列表。复选框列表是硬编码,如下所示:

<input type="checkbox" ng-model="characteristics.nontraditional" ng-true-value="non-tradtional" ng-false-value="">&#160; Non Traditional<br>
<input type="checkbox" ng-model="characteristics.metal" ng-true-value="metal" ng-false-value="">&#160; Metal<br>
<input type="checkbox" ng-model="characteristics.plancha" ng-true-value="plancha" ng-false-value="">&#160; Plancha<br>
<input type="checkbox" ng-model="characteristics.rocket" ng-true-value="rocket" ng-false-value="">&#160; Rocket<br>
<input type="checkbox" ng-model="characteristics.wick" ng-true-value="wick" ng-false-value="">&#160; Wick

我的ng-repeat看起来像这样:

<div ng-repeat="stove in stoves | filteredstoves:characteristics">

我的自定义过滤器如下所示:

stovecat.filter('filteredstoves', function() {
  return function(stoves, characteristics) { 
    alert(characteristics)
         }
    } 
}

加载页面时。警报包含“未定义”,预期未选中任何复选框。当我选择一个或多个复选框时,警报包含[对象对象],这很好,因为对象现在已传递到自定义过滤器中。如何访问传递到自定义过滤器的这些值,以便我可以相应地过滤列表?有什么我想念的吗?

谢谢大家!

1 个答案:

答案 0 :(得分:2)

带解决方案的Plunker:http://plnkr.co/edit/7PhNEADHW099w9kaqS7M?p=preview

模板:

<input type="checkbox" ng-model="characteristics.nontraditional">&#160; Non Traditional</input><br>
<input type="checkbox" ng-model="characteristics.metal">&#160; Metal</input><br>
<input type="checkbox" ng-model="characteristics.plancha">&#160; Plancha</input><br>
<input type="checkbox" ng-model="characteristics.rocket">&#160; Rocket</input><br>
<input type="checkbox" ng-model="characteristics.wick">&#160; Wick</input><br/>

<div ng-repeat="stove in stoves | filteredstoves:characteristics">{{stove.name}} - {{stove.characteristics}}</div>

过滤器:

stovecat.filter('filteredstoves', function() {
  return function(stoves, characteristics) {
    var result = stoves.slice(); // copy array
    angular.forEach(characteristics, function(value, key) {
      if(value) {
        for(var index = 0; index < result.length; index++) {
          stove = result[index];
          if(stove.characteristics.indexOf(key) == -1) {
            result.splice(index--,1);
          }
        }
      }
    });
    return result;
  }
});

只需浏览过滤器中的所有特征,然后删除不带它们的项目