Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS render HTML within double curly brace notation

Tags:

html

angularjs

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>
like image 589
Bob van Luijt Avatar asked Feb 11 '15 00:02

Bob van Luijt


People also ask

What is double curly brackets in HTML?

The double curly brackets are not HTML but scripting code. The term inside, interest, is a placeholder, sort of like the name and address in a form letter. The string {{interest}} will be replaced when the HTML template is converted into straight HTML that is sent over the network to the user.

How do you put curly braces in HTML?

“}” U+007D Right Curly Bracket Unicode Character.

What is double curly brackets in angular?

Displaying values with interpolationlink Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters.

Does HTML use curly braces?

It does nothing in HTML. It's actually invalid markup. Looks like maybe you have a template system that finds and replaces that before it gets rendered to the browser. Show activity on this post.


1 Answers

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>
like image 82
floribon Avatar answered Oct 27 '22 01:10

floribon