Sunday, 1 May 2016

AngularJS: Why is my HTML not rendering correctly?

I was recently faced with the problem that my solution required HTML to be rendered. Not a problem - bind it with ng-bind-html and all is good.

Or is it?

This solution falls on its head when we have embedded 'syle' in the HTML.

<div class="ExternalClass2F49307A49BF4FE3B48CB68350A1A9C6"><span style="color:rgb(0, 128, 0)">--My Sample Text in the RichText  Editor in SP2010--</span><div><br /></div>
<div><br /></div></div>

The solution is to used $sce (Strict Contextual Escaping) to format the output.

Controller:
$scope.trustAsHtml = function(string) {
    return $sce.trustAsHtml(string);
};

DOM/HTML:
<div data-ng-bind-html="trustAsHtml(myHtmlString)"></div>


No comments:

Post a comment