如何创建 angularjs 过滤器输出 HTML

阅读完《 AngularJS 教程步骤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>

问题是,浏览器将返回值逐字显示如下:

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

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

下面是 JSFiddle 的例子

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

有没有可能关闭这个特定过滤器的消毒?

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

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

但这不是我想要的。

81914 次浏览

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>

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

I have provided a working example.

Unless I am reading it wrong, you are approaching in the wrong way.

I think ng-class is the directive you need for this job and is safer than rendering to class attribute.

In your case just add object string with the id strings as the class and the value as the evaluated expression.

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

On a side note, you should only use directives (built-in and custom) to manipulate html/dom and if you needed a more complex html render you should look at directive instead.

Try this filter

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

requires angular-sanitize

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

Gist Link