AngularJs过滤器带有“或"状况? [英] AngularJs filter with "or" condition?

查看:59
本文介绍了AngularJs过滤器带有“或"状况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可在此处找到代码: https://plnkr.co/edit/gbbsEnXxVpLsxvtKsDxw?p=预览.过滤器 filter:{a:'x'} 起作用,并且仅显示一行.

The code is available here: https://plnkr.co/edit/gbbsEnXxVpLsxvtKsDxw?p=preview. The filter filter: { a : 'x' } works and only one row is shown.

问题:

  1. 似乎 filter:{a:'xxx'} 匹配 a 中的任何文本,只要该文本包含字符串 xxx .如果我想进行精确匹配怎么办?
  2. 如何实现:如果 a ='xxx'或b = 3 不使用 c ,则显示所有行?
  3. 也许最好在`model.dashbardRows上使用javascript代码?
  1. It seems filter: { a : 'xxx' } matches any text in a as long as the text contains the string xxx. What if I want to do exact matching?
  2. How to implement: show all the rows if a = 'xxx' or b = 3 not not use c?
  3. Maybe it's better to use javascript code on `model.dashbardRows?

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>

推荐答案

@Valery建议使用自定义过滤器是解决此问题的最佳方法.

As suggested by @Valery using custom Filter is the best solution around this.

这里是使用自定义过滤器(多个条件)的fork

dashboard.component.js

dashboard.component.js

.filter("optionalFilter",function(){
  //console.log("filter loads");
  return function(items, firstArgument,secondArgument){
    //console.log("item is ",items); // it is value upon which you have to filter
    //console.log("firstArgument is ",firstArgument);
    //console.log("secondArgument ",secondArgument);
    var filtered = [];
    angular.forEach(items, function(value, key) {
      //console.log("val ::",value);
      if(value.a == firstArgument || value.b == secondArgument){
       // console.log("val ::",value.a);
        this.push(value);
      }
    }, filtered);
    //console.log("val ::",filtered);
    return filtered;
  }

dashboard.component.html

dashboard.component.html

   <tr ng-repeat="i in model.dashboardRows | optionalFilter:'aaa':2">

有用的参考文献:

这篇关于AngularJs过滤器带有“或"状况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆