3

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?

2 Answers 2

2

That's a great answer. Building on that, you can reuse it greatly as a filter instead:

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 like this:

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

This becomes very usable when you have 3rd party scripts (let's say, an image gallery), and you have to pass data to it by html data-* attributes. The only way of doing it is by using filter.

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

Hope this helps someone :)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.