【问题标题】:How to have AngularJS output escaped HTML [duplicate]如何让 AngularJS 输出转义 HTML [重复]
【发布时间】:2013-12-24 13:16:01
【问题描述】:

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

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

我正在疯狂地尝试用 AngularJs 渲染它。

以下内容不起作用:

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

我认为这是正常的,因为 html 实际上已被转义。 我应该先取消它吗? Angular 是否能够通过一些可用的服务对 html 进行转义?

如果我像这样使用 $sce:

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

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

【问题讨论】:

  • 为什么不从服务器发送正确的 html?
  • 这是我下定决心要做的事情。但我认为传输 html 转义更安全。
  • 不明白为什么它会更安全,或者它会有什么不同
  • 您使用的是什么版本的 Angular? ng-bind-html-unsafe 在 1.2+ 版本中被移除,支持 ng-bind-html 和 $sce 服务
  • @max Favilli - 你能解决这个问题吗?解决办法是什么?

标签: javascript json angularjs html-escape-characters


【解决方案1】:

同时引入$sce 服务(angular 1.2),不再支持ng-bind-html-unsafe 指令。新指令是ng-bind-html。如果你使用这个,代码应该可以工作as documented

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

【讨论】:

  • 如果我不希望内部 html 的其余部分不被覆盖并且无法为自定义文本创建跨度标记怎么办
【解决方案2】:

使用这个指令:

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

不要忘记在您的应用模块上使用 angular sanitize。

在这里查看:http://docs.angularjs.org/api/ngSanitize

【讨论】:

  • @IlanBiala 我会详细说明。他的意思是将 ngSanitize 模块添加到您的应用程序中,如下所示: angular.module('myApp', ['ngSanitize']);并且还包括来自这里的 angular-sanitize.js 脚本ajax.googleapis.com/ajax/libs/angularjs/1.5.5/…(或您想要的任何版本).. 没有这些,ng-bind-html 将无法工作。希望对访问这里的人有所帮助。
猜你喜欢
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2019-03-02
  • 2020-06-16
  • 1970-01-01
相关资源
最近更新 更多