public

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

8 years ago

Latest Post Architectural Decision Record by Tim Sommer public

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.

ngSanitize

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:

ng-bind-html="entry.content"

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:

Html:

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

Controller:

$scope.SkipValidation = function(value) {
  return $sce.trustAsHtml(value);
};
Tim Sommer

Published 8 years ago

Comments?

Leave us your opinion.