AngularJS:用自定义样式绑定 html 字符串 [英] AngularJS: Bind html string with custom style
本文介绍了AngularJS:用自定义样式绑定 html 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将具有自定义样式的 html 字符串绑定到 DOM.但是 ngSanitize
从字符串中删除样式.
例如:
在控制器中:
$scope.htmlString = "<span style='color: #89a000'>123</span>!";
在 DOM 中:
将省略样式属性.结果将如下所示:
<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/控制器部分:
$scope.trustAsHtml = function(string) {返回 $sce.trustAsHtml(string);};
在 DOM/HTML 部分
I want to bind a html string with an custom style to the DOM. However ngSanitize
removes the style from the string.
For example:
In the controller:
$scope.htmlString = "<span style='color: #89a000'>123</span>!";
And in 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>
Instead of:
<div data-ng-bind-html="htmlString"><span style='color: #89a000'>123</span>!</div>
Question: How can I achieve this?
解决方案
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);
};
And in DOM/HTML part
<div data-ng-bind-html="trustAsHtml(htmlString)"></div>
这篇关于AngularJS:用自定义样式绑定 html 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文