Sunday, May 21, 2017

AngularJS: Insert HTML from a string || render HTML within double curly brace notation

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

No comments:

Post a Comment