Question

I've got a comments section on my site where I save htmlencoded comments in my database. So I added this comment-

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

and it saved in the database as-

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

All good but when I print it to my page

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

The ampersands are automatically changed to

&amp;

So the resulting string on the page will be-

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

Of course this won't show properly. I tried passing the commented to a parseAmper filter that replaces all encoded ampersands with & but it doesn't stick. How can I print ampersands properly?

Was it helpful?

Solution

You can use:

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;');
});

And here is a demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top