Tim Tim - 1 year ago 163
AngularJS Question

AngularJS: Bind html string with custom style

I want the bind a html string with an custom style to the DOM. However

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?

Answer Source

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download