AngularJS:更改HTML字符串的编码

时间:2014-08-07 13:58:12

标签: javascript html angularjs character-encoding

我有一个HTML格式的电子邮件附件,我想将其注入Angular页面。我试过这个:

$scope.email = $sce.trustAsHtml(email);

<div ng-bind-html="email"></div>

它确实显示HTML,但是有些字符像你在这里看到的那样混乱(不介意像素化文本,我必须保护人们的隐私:)): enter image description here

我认为使用 iframe 会有所帮助,但结果是一样的:

<iframe srcdoc="{{email}}"></iframe>

因此我假设我需要以编程方式更改该电子邮件的编码(电子邮件变量)。有办法怎么做?

1 个答案:

答案 0 :(得分:0)

我曾经遇到类似的问题,花了几个小时后,这是我提出的最佳解决方案:):

我首先使用ng-include:

将html包含到我的页面中
    <ng-include src="'partials/hello.html'" render-html></ng-include>

我的hello.html partial中有以下编码的html:

&lt;div&gt; hello &lt;/div&gt;

ng-include正确解码了我的html并将其作为文本放在屏幕上

<div> hello </div>

最后,我按如下方式实现了我的指令render-html:

myApp.directive('renderHtml',
    function () {
        return {
            link: function (scope, element, attrs) {
                element.html($(element).text());
            }
        };
});  

通过替换,我的html被正确处理并呈现在屏幕上,只显示div标签中的'hello'。

hello