使用Angular将文本渲染为HTML

4

我正在尝试使用ng-bind将文本渲染为HTML,如文档所示

<div ng-bind-html="text"></div>

问题在于Angular会移除style属性并呈现如下内容:

"<mark style='background-color:#FF9DFF;'>APPLE</mark>."

转换为:

<mark>APPLE</mark>

如何将HTML呈现并保留样式? 我正在使用Angular版本1.2.6。

请注意,$sce 版本为 1.2 及以上。 - wayne
2个回答

4
当您在控制器中使用ng-bind-html时,可以尝试使用此函数。
$sce.trustAsHtml('myHTML'); //$sce would be the parameter with $scope in module

希望这能奏效。

$NgSanitize文档


2
首先需要引用angular-sanitize.js
<div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>

然后在控制器中添加这个方法。
pk.controller("createBlog", function($scope, $sce){
   //ace needs to be injected in the controller.
   $scope.deliberatelyTrustDangerousSnippet = function() {
       return $sce.trustAsHtml($scope.htmlcontent); //html content is th binded content.
   };
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接