HTML encoded String not translating correctly in AngularJS
Asked Answered
D

2

2

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?

Danielladanielle answered 14/7, 2015 at 16:40 Comment(0)
U
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.

Ubald answered 14/7, 2015 at 17:18 Comment(0)
P
1

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 :)

Poorly answered 4/8, 2016 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.