HTML encoded String not translating correctly in A

2019-07-11 19:05发布

问题:

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?

回答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.



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