如何让 AngularJS 输出转义 HTML [英] How to have AngularJS output escaped HTML

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

问题描述

我从服务器获取 JSON 数据,其中一个字段包含转义的 html(实际上是电子邮件正文):

&lt;html>\r\n<head>\r\n<meta http-equiv=&quot;Content-Type&quot;内容="文本/html;charset=iso-8859-1&quot;>\r\n</head>\r\n<body dir=&quot;auto&gt;\r\n&lt;div>Buonasera, ho verificato i dati sul mio account ed il numero di cell che vi ho fornito&lt;/div>\r\n<div&gt;<br&gt;\r\n&lt;a(更多...)

我越来越想用 AngularJs 渲染它了.

以下不起作用:

我认为这是正常的,因为实际上 html 已被转义.我应该先逃避它吗?Angular 是否能够使用某些可用服务对 html 进行转义?

如果我像这样使用 $sce:

scope.mail.htmlbody = $sce.trustAsHtml(scope.mail.htmlbody);

显示源html,检查元素我可以看到引用的内容.换句话说,在页面中显示源 html 而不是呈现的 html.也许我错过了什么?

解决方案

同时引入 $sce 服务(angular 1.2),支持 ng-bind-html-unsafe 指令被删除.新指令是 ng-bind-html.如果您使用它,代码应该可以如文档所述:

 

I am getting JSON data from the server, one of the field contains escaped html (an email body actually):

&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot;&gt;\r\n&lt;/head&gt;\r\n&lt;body dir=&quot;auto&quot;&gt;\r\n&lt;div&gt;Buonasera, ho verificato i dati sul mio account ed il numero di cell che vi ho fornito&lt;/div&gt;\r\n&lt;div&gt;&lt;br&gt;\r\n&lt;a (more...)

I am getting crazy at trying to render it with AngularJs.

The following is not working:

<div ng-bind-html-unsafe="mail.htmlbody"></div>

Which I believe is normal because the html is in fact escaped. Should I unescape it first? Is Angular capable of unescaping html with some available service?

If I use $sce like this:

scope.mail.htmlbody = $sce.trustAsHtml(scope.mail.htmlbody);

The source html is displayed, inspecting the element I can see the content is quoted. In other words in the page the source html is displayed instead of the html being rendered. Maybe I am missing something?

解决方案

At the same time $sce service was introduced (angular 1.2), support for ng-bind-html-unsafe directive was dropped. The new directive is ng-bind-html. If you use this, the code should work as documented:

 <div ng-bind-html="mail.htmlbody"></div>

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

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