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

前端之家收集整理的这篇文章主要介绍了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>

解决方法

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

这里是过滤器样本……

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 ……

猜你在找的Angularjs相关文章