AngularJs过滤“或”条件?

时间:2016-09-18 05:13:37

标签: javascript angularjs

代码可在此处获取:https://plnkr.co/edit/gbbsEnXxVpLsxvtKsDxw?p=preview。过滤器filter: { a : 'x' }有效,只显示一行。

问题:

  1. 似乎filter: { a : 'xxx' }匹配a中的任何文字,只要该文字包含字符串xxx即可。如果我想进行精确匹配怎么办?
  2. 如何实施:如果a = 'xxx' or b = 3不使用c,则显示所有行?
  3. 也许最好在`model.dashbardRows?
  4. 上使用javascript代码

    dashboard.component.js

    (function () {
        'use strict';
        angular.module('testModule', []) 
        .component('dashboard', {
          templateUrl: 'dashboard.component.html',
          controllerAs: 'model',
          controller: [controller] 
        });
    
        function controller() {
          var model = this;
          model.dashboardRows = [
            {a:'xxx', b:1, c:'ss'}, 
            {a:'yyy', b:2, c:'tt'}, 
            {a:'zzz', b:3, c:'uu'}];
        }
    })();
    

    dashboard.component.html

    <div>
      Test
      <table>
        <tr ng-repeat="i in model.dashboardRows | filter: { a : 'x' }">
          <td>{{i.a}}</td>
          <td>{{i.b}}</td>
        </tr>
      </table>
    </div>
    

2 个答案:

答案 0 :(得分:1)

查看filter filter文档,您可以传入可选的comparator参数。

  

true:函数的简写(实际,预期){return angular.equals(actual,expected)}。这基本上是对预期和实际的严格比较。

请注意,这是区分大小写的(因为字符串比较在JS中区分大小写)。

此外,在页面底部还有一个示例,演示过滤所有或仅一个属性。如果您的过滤很复杂,或者您的源数据很大,那么在控制器中过滤也有助于提高可读性和性能。

答案 1 :(得分:1)

我认为你应该使用自定义过滤器

module.filter('myFilter', function(){
   return function(input){
      return input.filter(yourFilterFn);
   };
});

ng-repeat="item in items | myFilter"