HTML encoded string not translating correctly in AngularJS

I have an HTML encoded string:

Sign up and get <span class="strong">Something for FREE!</span> 

When I use ngSanitize and ng-bind-html in my template as follows:

 <p ng-bind-html="someText"></p> 

I am returning an HTML decoded string:

 Sign up and get <span class="strong">Something for Free!</span> 

But it literally shows the HTML-decoded string in the browser, instead of displaying the HTML correctly.

How can I render the correct HTML in the DOM?

+2
angularjs ngsanitize
Jul 14 '15 at 16:40
source share
2 answers

You can decode the html string first. Here is a working plunker example.

 angular.module('app', ['ngSanitize']) .controller('ctrl', ['$scope', '$sanitize', function($scope, $sanitize){ $scope.someText = htmlDecode("Sign up and get &lt;span class=&quot;strong&quot;&gt;Something for FREE!&lt;/span&gt;"); function htmlDecode(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; } }]); 

** Decode function taken from this answer.

+1
Jul 14 '15 at 17:18
source share

This is a great answer. Based on this, you can use it as a filter instead of:

 angular.module('app', ['ngSanitize']) .filter('decoded', [ '$sanitize', function($sanitize) { function htmlDecode(input) { var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; } return function(input) { return htmlDecode(input); } }]) 

Then use it as follows:

 <p ng-bind-html="scope_with_data | decoded"></p> 

This becomes very convenient if you have third-party scripts (say, an image gallery), and you need to transfer data using the html data- * attributes. The only way to do this is to use a filter.

 <div data-title="scoped_data.title | decoded "></div> 

Hope this helps someone :)

+1
Aug 04 '16 at 13:46 on
source share



All Articles