47

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?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Tim
  • 5,521
  • 8
  • 36
  • 69

5 Answers5

71

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>
Pavel Arapov
  • 847
  • 7
  • 8
51

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>

grigson
  • 3,458
  • 29
  • 20
13

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>
Beyers
  • 8,968
  • 43
  • 56
  • Isn't there another way? Preferably from withing the DOM itself. This one doesn't end up clean in my situation. – Tim Feb 01 '14 at 21:40
  • Apart from completely disabling $sce http://docs.angularjs.org/api/ng.$sce#example_can-i-disable-sce-completely (not recommended), there isn't a build-in way to handle this within the DOM itself that I'm aware of. Pretty sure you should be able to get this done writing your own custom directive. – Beyers Feb 01 '14 at 22:19
0

You should create your own custom directive that will have the html as template or reference it with templateUrl. Within the html you can use ng-style to add an object as your style.

Here's an example: http://jsfiddle.net/tomepejo/5AsQE/

Tome Pejoski
  • 1,582
  • 2
  • 10
  • 34
0

You can use textAngular, couse ngSanitize whitelists are not flexible ( see this issues for more details: https://github.com/angular/angular.js/issues/5900)

bsm
  • 556
  • 4
  • 6
  • Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Heretic Monkey Nov 01 '16 at 18:47