Bind HTML string with custom style

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?


Solution 1:

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>

Solution 2:

What about custom angular filter? This works in 1.3.20

angular.module('app.filters')
    .filter('trusted', function($sce){
        return function(html){
            return $sce.trustAsHtml(html)
        }
     })

Use it like <div ng-bind-html="model.content | trusted"></div>

Solution 3:

If you trust the html, then you can use $sce.trustAsHtml to explicitly trust the html. Quick example:

In controller (remember to inject $sce into your controller):

$scope.htmlString = $sce.trustAsHtml("<span style='color: #89a000'>123</span>!");

And in DOM, same as what you had:

<div data-ng-bind-html="htmlString"></div>