【问题标题】:Angular filter that generates html生成 html 的 Angular 过滤器
【发布时间】:2021-03-04 18:41:32
【问题描述】:

我有一个小的角度过滤器,它插入一个(引导)图标来代替真值。 它可以工作,但 html 已编码:

  var conApp = angular.module('conApp', []);
  conApp.filter('trueIcon', function($filter){
    return function(booleanValue){
        return booleanValue ? '<i class="icon-ok"></i>' : '';
    }
  });

我必须实现另一个过滤器来解码 html 吗? 有这样做的“角度”方式吗?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你需要使用ng-bind-html来渲染html。

    <span ng-bind-html="foo | trueIcon"></span>
    

    也就是说……那真的不是过滤器的用途。过滤器更多地用于清理写入视图的数据,而不是生成视图/DOM 本身的元素。您最好为此创建一个指令:

    app.directive('trueIcon', function() {
       return {
          restrict: 'E',
          template: '<i ng-class="{\'icon-ok\': value, \'icon-not-okay\': !value}"></i>',
          scope: {
             value: '='
          }
       };
    });
    
    <true-icon value="foo"></true-icon>
    

    【讨论】:

    • @blesh 在这种情况下也为你 +1 :-) 你也在回答大量的问题!
    • 我为什么不能将我的指令定义为'true-icon'?指令名称总是驼峰式的吗?
    • Angular 只希望它们是驼峰式的。 IIRC,如果你用破折号声明它们,它们就不起作用。
    • 很好,谢谢。我正在“清理” \r\n 并将其替换为
      所以希望不会过多地违反过滤器的预期用途。
    • 你为什么说这不是过滤器的用途?在 Angular 教程中,first example of custom filters 做同样的事情,但使用 UTF 字符而不是 html 标记。
    【解决方案2】:

    默认情况下,AngularJS 正在清理表达式评估的结果。要将 HTML 显示为标记,您有 2 个选项:

    虽然上述内容将使您的过滤器正常工作,但也许您应该考虑将其转换为指令?

    【讨论】:

    • +1 给你,因为我们都说了基本相同的话......而且我经常看到你。
    • 我认为您的链接不再有效。
    【解决方案3】:

    对于将 \r\n 转换为
    的情况,我发现的另一种方法是使用小函数和 *ngFor。

    在你的 ts 文件中,添加函数

    splitLines(text: String): string[] {
      return text.split(/\r?\n/);
    }
    

    在html中

    <span *ngFor="let row of splitLines(multilineStringVariable)">
      {{row}}<br/>
    </span>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-20
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多