Using AngularJS $sce trustAsHtml to display raw HTML to page

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

If you need to display raw HTML content to the page view with AngularJS, you can use the $sce service that comes with AngularJS.  $sce stands for Strict Contextual Escaping.  The service has trustAsHTML method with take some arbitrary text or HTML.

In the previous tutorial, we displayed some text content such as “Copyright 2015” to a page using code like this…

displaying content works

displaying content works

But if we try to put HTML content (such as a link to privacy policy page), …

trying to output this HTML

trying to output this HTML

it will escape the tags and make safe the HTML prior to rendering.  And you end up with this,

escaped HTML

escaped HTML

which is not what you want.

So what you have to do is to inject the $sce service into the controller and use its trustAsHtml method…

using trustAsHtml

using trustAsHtml

Nope, still doesn’t work.

That is because it only works if we use ng-bind-html instead of simple output using the double curly braces.  So we change to …

ng-bind-html

using ng-bind-html

And now it works as expected with our correctly rendered raw HTML…

rendered raw html

rendered raw html