AngularJS自动HTML编码&符号

时间:2014-01-26 21:50:33

标签: angularjs html-encode

我的网站上有一个评论部分,我在我的数据库中保存了htmlencoded注释。所以我添加了这条评论 -

"testing" `quotes` \and backslashes\ <b>and html</b>

并将其作为 -

保存在数据库中
&quot;testing&quot; &#039;quotes&#039; \and backslashes\ &lt;b&gt;and html&lt;/b&gt;

一切都很好但是当我把它打印到我的页面时

<li class="media" ng-repeat="comment in comments">
    <a class="pull-left" href="#">
      <img class="media-object" src="/{{comment.thumb}}" width="24" alt="{{comment.username}}">
    </a>
    <div class="media-body">
      <h5 style='margin: 0px;'><a href="/profile/{{comment.username}}">{{comment.username}}</a></h5>
      <p>{{comment.message}}</p>
    </div>
</li>

&符号会自动更改为

&amp;

因此页面上的结果字符串将是 -

&amp;quot;testing&amp;quot; &amp;#039;quotes&amp;#039; \and backslashes\ &amp;lt;b&amp;gt;and html&amp;lt;/b&amp;gt;

当然这不会正常显示。我尝试将注释传递给parseAmper过滤器,该过滤器用&amp;替换所有编码的&符号。但它不坚持。如何正确打印&符号?

1 个答案:

答案 0 :(得分:2)

您可以使用:

HTML

<body ng-app="demo" ng-controller="MainCtrl">
  <span ng-bind-html="foo"></span>
</body>

的JavaScript

angular.module('demo', []);

var demo = angular.module('demo').controller('MainCtrl', function ($scope, $sce) {
  $scope.foo = $sce.trustAsHtml('&quot;testing&quot; &#039;quotes&#039; \and backslashes\ &lt;b&gt;and html&lt;/b&gt;');
});

here is a demo