如何动态禁用ng-repeat内的过滤器

时间:2014-06-08 19:51:15

标签: angularjs checkbox filter angularjs-ng-repeat

可以使用复选框删除过滤器吗?

如果选中复选框,则会禁用ng-repeat内的过滤器。例如,如果选中了 countryfilter winetypefilter 复选框,则会禁用相关过滤器。

原始代码(已启用过滤器)

<li ng-repeat="wine in wines | winetypefilter:winetypes| countryfilter:countrytypes | stylefilter:styletypes">
                {{wine.name}} is a {{wine.type}} with {{wine.style}} style from {{wine.country}}
</li>

(已使用复选框禁用过滤器, countryfilter winetypefilter ) 结果:

<li ng-repeat="wine in wines | stylefilter:styletypes">
            {{wine.name}} is a {{wine.type}} with {{wine.style}} style from {{wine.country}}
</li>

1 个答案:

答案 0 :(得分:5)

当然你可以动态启用禁用你的过滤器...有很多方法可以做到这一点我想到的最简单的解决方案就是发送第三个参数作为布尔值来检查过滤器是否启用... < / p>

这里是过滤器样本......

app.filter('winetypefilter', function () {
  return function(input, filter, isEnable) {
    // if isEnable then filter out wines
    if (isEnable) {
      var result = [];
      angular.forEach(input, function (wine) {
          angular.forEach(filter, function (isfiltered, type) {
              if (isfiltered && type === wine.type) {
                  result.push(wine);
              }
          });
      });
      return result;
    } 
    // otherwise just do not any filter just send input without changes
    else{
      return input
    }
  };
});

这里是PLUNKER ...