11

I have JSON variables that contain HTML.

By doing: {{source.HTML}} Angular is showing &lt; and &gt; instead of < and >.

What can I do to have Angular render the actual HTML?



UPDATE:
This is my controller:

app.controller('objectCtrl', ['$scope', '$http', '$routeParams',
  function($scope, $http, $routeParams) {

    var productId = ($routeParams.productId || "");

    $http.get(templateSource+'/object?i='+productId)
       .then(function(result) {
          $scope.elsevierObject = {};
          angular.extend($scope,result.data[0]);
        });
  }]);

Inside my HTML i can then use:

<div>{{foo.bar.theHTML}}</div>
3
  • possible duplicate of How to have AngularJS output escaped HTML Commented Feb 11, 2015 at 1:00
  • look into ng-bind-html Commented Feb 11, 2015 at 1:04
  • Hi @Seth it's not a duplicate, this one focusses on the curly brace notation. Commented Feb 11, 2015 at 1:08

1 Answer 1

24

Do you want to show the HTML (like <b>Hello</b>) or render the HTML (like Hello) ?

  • If you want to show it, the curly bracket is enough. However if the html you have has html entities (like &lt;stuff) you need to manually unescape it, see this SO question.

  • If you want to render it, you need to use the ng-bind-html directive instead of curcly bracket (which, FYI, is a shortcut to the ng-bind directive). You need to tell Angular that the content injected into that directive is safe, using $sce.trustAsHtml.

See example of both cases below:

angular.module('test', []).controller('ctrl', function($scope, $sce) {
  $scope.HTML = '<b>Hello</b>';
  
  $scope.trust = $sce.trustAsHtml;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="ctrl">
  <div>Show: {{HTML}}</div>
  <div>Render: <span ng-bind-html="trust(HTML)"></span></div>
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Your html and controller are different. I don't see where you set $scope.foo.bar.theHTML. Note that I have updated my answer with more information
Can't you just use <span ng-bind-html="HTML"/>?
You can. Just make sure you are referencing ngSanitize.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.