Using ngSanitize to render HTML strings in Angular

Using ngSanitize to render HTML strings in Angular

I've been playing around with Angular the last couple of weeks. Some functionalities are really easy to implement. Others are just a pain in the ass in comparison to competing SPA frameworks like Durandal or Ember. An example? Rendering an Html string in a div or p tag.


You will need to include the ngSanitize module, as rendering Html is not included in the Angular core.
Documentation on ngSanitize can be found here.
The module can be installed using Bower, take a look here.

Include the module

Start of by including the angular-sanitize.js script in your Html:

<script src="angular.js">
<script src="angular-sanitize.js">

Then load the module in your application by adding it as a dependent module:

angular.module('app', ['ngSanitize']);

The 'ng-bind-html' attribute

You can now use ng-bind-html in your Html:


Important: The ng-bind-html functionality will validate your Html and log occuring errors to the console window. If you want to disable this validation, say for production environments, use the following code:


<p ng-bind-html="SkipValidation(entry.summary)"></p>


$scope.SkipValidation = function(value) {
  return $sce.trustAsHtml(value);
Newer Articles
Older Articles