HTML encoded String not translating correctly in AngularJS

南笙酒味 提交于 2019-12-11 02:57:09

问题


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



来源:https://stackoverflow.com/questions/31412551/html-encoded-string-not-translating-correctly-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!