【问题标题】:Angular: Use Filter and OR Operator PipeAngular:使用过滤器和 OR 运算符管道
【发布时间】:2016-01-12 23:16:11
【问题描述】:

有没有办法在 AngularJS 表达式中使用过滤器管道和 OR 管道。例如:

{{ price | currency || "no price set" }}

这可能吗?

感谢任何帮助。提前致谢!

【问题讨论】:

    标签: angularjs filter pipe


    【解决方案1】:

    虽然可读性不强,但可以使用三元运算符:

    {{ price ? (price | currency) : "no price set" }}
    

    js fiddle

    上述解决方案有一个缺点:如果定义了价格但等于零(假设这是您的应用程序中价格的有效值),您将得到 "no price set" em> 为零是 falsy。 您可以通过将函数 angular.isDefined 暴露于作用域来解决这个问题:

    $scope.isDefined = angular.isDefined;
    
    {{isDefined(price) ? (price | currency) : "no price"}}
    

    但是,总而言之,定义一个自定义过滤器会更简洁:

    app.filter('priceFilter', function ($filter) {
      return function (input) {
        return angular.isDefined(input) ? $filter('currency')(input) : 'No price set';
      };
    });
    
    {{price | priceFilter}}
    

    updated js fiddle

    【讨论】:

      【解决方案2】:

      我请客:

      import { Pipe, PipeTransform } from '@angular/core';
      
      @Pipe({
        name: 'filter'
      })
      export class FilterPipe implements PipeTransform {
      
        transform(items: Array<any>, conditions: {[field: string]: any}): Array<any> {
          return items.filter(item => {
            let allBlanks = true;
            for (let field in conditions) {
              let itemField = item[field] ? item[field].toLowerCase() : '';
              let conditionField = conditions[field] !== undefined ? conditions[field].toLowerCase() : '';
              if(conditionField !== '') {allBlanks = false;}
              if (itemField.indexOf(conditionField) !== -1 && conditionField !== '') {
                return true;
              }
            }
            return allBlanks;
          });
        }
      
      }
      

      【讨论】:

        【解决方案3】:

        您可以在括号中填写要评估的内容:

        {{ (price | currency) || "no price set" }}
        

        这样no price set 将在price | currency 被评估为false 时呈现。

        【讨论】:

          猜你喜欢
          • 2018-03-19
          • 2021-12-11
          • 2017-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-16
          相关资源
          最近更新 更多