生成html的角度过滤器

时间:2013-02-04 17:44:45

标签: javascript angularjs

我有一个小角度滤镜,可以插入(引导)图标来代替真值。 它有效,但html编码:

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

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

3 个答案:

答案 0 :(得分:28)

您需要使用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>

答案 1 :(得分:6)

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

虽然以上内容会使您的过滤器工作,但是您应该考虑将其转换为指令吗?

答案 2 :(得分:0)

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

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

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

在 html 中

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