本文介绍了AngularJS:以自定义样式绑定html字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将具有自定义样式的html字符串绑定到DOM.但是ngSanitize
会从字符串中删除样式.
I want to bind a html string with an custom style to the DOM. However ngSanitize
removes the style from the string.
例如:
在控制器中:
$scope.htmlString = "<span style='color: #89a000'>123</span>!";
在DOM中:
<div data-ng-bind-html="htmlString"></div>
将省略样式属性.结果将如下所示:
Will omit the style attribute. The result will look like:
<div data-ng-bind-html="htmlString"><span>123</span>!</div>
代替:
<div data-ng-bind-html="htmlString"><span style='color: #89a000'>123</span>!</div>
问题:我该如何实现?
推荐答案
正如已经提到的@Beyers,您必须使用$sce.trustAsHtml()
,直接将其用于DOM中,您可以这样做,JS/controller部分:
As already mentioned @Beyers, you have to use $sce.trustAsHtml()
, to use it directly into the DOM, you could do it like this, JS/controller part:
$scope.trustAsHtml = function(string) {
return $sce.trustAsHtml(string);
};
在DOM/HTML部分
And in DOM/HTML part
<div data-ng-bind-html="trustAsHtml(htmlString)"></div>
这篇关于AngularJS:以自定义样式绑定html字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!