如何创建输出 HTML 的 angularjs 过滤器 [英] How to create angularjs filter which outputs HTML

查看:25
本文介绍了如何创建输出 HTML 的 angularjs 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读AngularJS 教程第 9 步后我已经创建了自己的 AngularJS 过滤器,它应该将布尔数据转换为 html.

After reading AngularJS tutorial step-9 I have created my own AngularJS filter, which should convert boolean data into 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 代码:

Here is my HTML code:

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

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

The problem is that borwser displays returned value literally as:

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

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

not as icons (or rendered html) that should appear.

这里是 JSFiddle 示例

我认为在此过程中进行了一些消毒.

I think that some sanitisation occurs during this process.

是否可以为此特定过滤器关闭此清理?

Is it possible to turn this sanitization off for this specific filter?

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

Also I know how to display icons by not returning HTML output from filter but rather just 'ok' or 'remove' text which I can then substitute to:

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

但这不是我想要的.

推荐答案

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

You should use the ng-bind-html directive (require to import the sanitize module and js file): https://docs.angularjs.org/api/ng/directive/ngBindHtml

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

您还需要导入 CSS(我猜是Bootstrap)才能在运行时看到图标.

You also need to import the CSS (Bootstrap I guess) to be able to see the icon when it works.

我提供了一个工作示例.

这篇关于如何创建输出 HTML 的 angularjs 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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