AngularJS: binding HTML code with ng-bind-html and $sce.trustAsHtml

I am working on a project in which based on some user interactions I am calling a service on the server and receive some pieces of HTML code which I need to display in the UI.

Of course I could just inject them in the DOM but to keep it clean I wanted to just store the HTML in the scope and bind it to an HTML tag. Basically doing something like this:

<!DOCTYPE html>
<html>

<head>
  <script src="https://code.angularjs.org/1.4.0-beta.6/angular.js" data-semver="1.4.0-beta.6" data-require="angular.js@*"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
  <div ng-bind-html="myHtmlVar"></div>
</body>

</html>

The JavaScript code being:

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.myHtmlVar= "<a href='http://benohead.com'>benohead.com</a>";
});

This will unfortunately not work and you will get the following error message in the JavaScript console:

Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.

This basically means that the value we provided to ng-bind-html is not inherently safe and is also not marked as safe. So we need to mark it as trustworthy. This can be done by using $sce.trustAsHtml. An easy fix to the problem is to use the following:

app.controller('myCtrl', function($scope, $sce) {
    $scope.myHtmlVar= $sce.trustAsHtml("<a href='http://benohead.com'>benohead.com</a>");
});

If you do not want to add the calls to trustAsHtml everywhere in your code, you can also introduce a function in your scope and reference it in your page:

app.controller('myCtrl', function($scope, $sce) {
    $scope.myHtmlVar= "<a href='http://benohead.com'>benohead.com</a>";
    
    $scope.trustAsHtml = function(html) {
      return $sce.trustAsHtml(html);
    }
});

This function can then be called in the ng-bind-html attribute:

<div ng-bind-html="trustAsHtml(myHtmlVar)"></div>

Another way to do it is to define a filter which works in exactly the same way as the trustAsHtml function above:

app.filter('trustAsHtml', function($sce) {
  return function(html) {
    return $sce.trustAsHtml(html);
  };
});

app.controller('myCtrl', function($scope, $sce) {
  $scope.myHtmlVar = "<a href='http://benohead.com'>benohead.com</a>";
});

And use it like this:

<div ng-bind-html="myHtmlVar | trustAsHtml"></div>

Also note that if you want to set the HTML to the scope variable and then perform some DOM manipulation on this HTML code, you’ll run into a problem, because as long as your code is running, the data binding won’t be reflected until you return. Here is such an example:

app.controller('myCtrl', function($scope, $sce, $http) {
	$scope.myHtmlVar = "<a href='http://benohead.com'>benohead.com</a>";

	$scope.getHtmlCode = function (serviceParameter) {
		var responsePromise = $http.post("my-service-url", JSON.stringify(serviceParameter));
		responsePromise.success(function (data) {
			$scope.myHtmlVar = data;
			$scope.manipulateDom();
		});
	};
	
	$scope.manipulateDom = function () {
		//do some DOM manipulation on the retrieved HTML code...
	});
});

In order to execute some additional code, you’ll have to wrap it using $timeout:

app.controller('myCtrl', function($scope, $sce, $http, $timeout) {
	$scope.myHtmlVar = "<a href='http://benohead.com'>benohead.com</a>";

	$scope.getHtmlCode = function (serviceParameter) {
		var responsePromise = $http.post("my-service-url", JSON.stringify(serviceParameter));
		responsePromise.success(function (data) {
			$scope.myHtmlVar = data;
			$timeout(function() {
				$scope.manipulateDom();
			});			
		});
	};
	
	$scope.manipulateDom = function () {
		//do some DOM manipulation on the retrieved HTML code...
	});
});

 

4 thoughts on “AngularJS: binding HTML code with ng-bind-html and $sce.trustAsHtml

  1. THANK YOU SO MUCH!!! I lost like 3 hours looking for this answer! this made the trick for me:

    $scope.trustAsHtml = function(html) {
    return $sce.trustAsHtml(html);
    }

    Thanks again!

    Bye!

  2. can you please give me one example where I fetch HTML form residing in json form and then performing DOM manipulation (eg:deleting first name element i.e input box )

Leave a Reply

Your email address will not be published. Required fields are marked *