HTML编码的字符串在AngularJS中无法正确翻译
问题描述:
我有一个这样的HTML编码字符串:
I have an HTML encoded string like this:
Sign up and get <span class="strong">Something for FREE!</span>
当我在模板中使用ngSanitize和ng-bind-html时,如下所示:
When I use ngSanitize and ng-bind-html in my template like this:
<p ng-bind-html="someText"></p>
我取回HTML解码的字符串:
I get back the HTML decoded string:
Sign up and get <span class="strong">Something for Free!</span>
但是它实际上是在浏览器中显示HTML解码的字符串,而不是正确呈现HTML.
But it literally shows the HTML decoded string in browser, instead of rendering the HTML correctly.
如何让它在DOM中呈现正确的HTML?
How can I have it render the correct HTML in the DOM?
答
您可以先解码html字符串.这是一个有效的 plunker 示例.
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 <span class="strong">Something for FREE!</span>");
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.