Friday, March 13, 2015

AngularJS output trusted HTML to view using Strict Contextual Escaping

With AngularJS if you simply output a string of HTML to the page, it will be output as straight text rather than output as HTML. Using the ng-bind-html tag the HTML can then be output to the view/page as follows:
<div ng-bind-html="MyHtmlVar"></div>
However as of AngularJS version 1.3 the HTML is not considered trusted to be output to the page and the following error would occur "Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.". In the controller you would need to use $sce.trustAsHtml() to set the HTML as safe.
$scope.MyHtmlVar = $sce.trustAsHtml(inputString)
Also don't forget to reference $sce (Strict Contextual Escaping service) in the controller definition.

In the case of user entered HTML (such as commenting) it is recommended that you sanitize the HTML using a library before setting it to trusted.

You can also disable the need for SCE completely (meaning ng-bind-html will work without errors), however this would only be recommended for existing projects that would require significant re-factoring. For new projects there is very little code overhead in using SCE and the security benefits are worth the effort.

No comments:

Post a Comment