Sev Sev - 10 months ago 43
AngularJS Question

HTML encoded String not translating correctly in AngularJS

I have an HTML encoded string like this:

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

When I use ngSanitize and ng-bind-html in my template like this:

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

I get back the HTML decoded string:

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

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

How can I have it render the correct HTML in the DOM?


You can decode the html string first. Here's 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.