【问题标题】:How to create angularjs filter which outputs HTML如何创建输出 HTML 的 angularjs 过滤器
【发布时间】:2012-10-26 10:31:11
【问题描述】:

看完AngularJS tutorial step-9 我创建了自己的 AngularJS 过滤器,它应该将布尔数据转换为 html。

这是我的过滤代码:

angular.module('phonecatFilters', []).filter('iconify', function () { // My custom filter
    return function (input) {
        return input ? '<i class="icon-ok"></i>' : '<i class="icon-remove"></i>';
    }
});

这是我的 HTML 代码:

<dt>Infrared</dt>
  <dd>{{phone.connectivity.infrared | iconify }}"></dd>

问题是 borwser 将返回值显示为:

<i class="icon-ok"></i>

不是应该出现的图标(或呈现的 html)。

Here is JSFiddle example

我认为在此过程中会进行一些消毒。

是否可以针对此特定过滤器关闭此清理功能?

我还知道如何通过不从过滤器返回 HTML 输出来显示图标,而只是返回“确定”或“删除”文本,然后我可以替换为:

<i class="icon-{{phone.connectivity.infrared | iconify}}"><i>

但这不是我想要的。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您应该使用 ng-bind-html 指令(需要导入 sanitize 模块和 js 文件): https://docs.angularjs.org/api/ng/directive/ngBindHtml

    <span ng-bind-html='phone.connectivity.infrared | iconify'></span>
    

    您还需要导入 CSS(我猜是Bootstrap)才能在图标工作时看到它。

    我提供了working example

    【讨论】:

    • 嗯,这是我知道用 angularJS 输出原始 html 的唯一方法,而且这种绑定只允许在属性上使用,所以你没有太多选择,你可以编写自己的指令来接受 cmets 或元素绑定,以bind-html的源码为起点:github.com/angular/angular.js/blob/master/src/ngSanitize/…
    • 指令可能是这里最好的解决方案 但它并不比您的解决方案短 ;)
    • 需要注意的是,您需要包含angular-sanitize.js 文件才能使其工作。如果你想在不包含这个额外库的情况下做同样的事情,你可以使用ng-bind-html-unsafe 指令。
    • angular 2.x 丢弃 ng-html-bind-unsafe 并要求将 html 内容明确标记为“安全” - 请参阅:docs.angularjs.org/api/ng.$sce#Example
    • 应该有一个默认过滤器html_safe:{{myContent | myFilter | html_safe}}
    【解决方案2】:

    除非我读错了,否则你就是走错路了。

    我认为ng-class 是您完成这项工作所需的指令,并且比渲染到类属性更安全。

    在您的情况下,只需添加带有 id 字符串作为类和值作为评估表达式的对象字符串。

    <i ng-class="{
    'icon-ok':!phone.connectivity.infrared,
    'icon-remove':phone.connectivity.infrared
    }"></i>'
    

    附带说明,您应该只使用指令(内置和自定义)来操作 html/dom,如果您需要更复杂的 html 渲染,您应该查看指令。

    【讨论】:

    • 很好的解决方案。或者简单一点:&lt;i ng-class="phone.connectivity.infrared ? 'icon-ok' : 'icon-remove'"&gt;&lt;/i&gt;
    【解决方案3】:

    试试这个过滤器

    filter('trust', ['$sce',function($sce) {
      return function(value, type) {
        return $sce.trustAs(type || 'html', value);
      }
    }]);
    

    需要angular-sanitize

    var app = angular.module("myApp", ['ngSanitize']);
    

    Gist Link

    【讨论】:

      猜你喜欢
      • 2013-02-05
      • 2015-10-29
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      相关资源
      最近更新 更多