ng-tip 1: How to use ngSanitize

Bashar Ayyash
1 min readDec 18, 2014

--

Today I wanted to render html tags in angularjs app, I tried at first to use the $scope.variable = ‘Hello <strong>World!</strong>’; inside the controller and in the html page {{variable}} I got a raw html like this:

Hello <strong>World!</strong>

I searched for a while and found out that angularjs escape expressions so to make html tags render correctly I should do the following:

  • Download angular-sanitize module and include it in the html page
  • add ngSanitize in the module dependencies, var app = angular.module(‘myApp’, [‘ngSanitize’]);
  • Add the required expression in the controller: $scope.variable = ‘Hello <strong>World!</strong>’;
  • In the view page: <div ng-bind-html=”variable”></div>

Now the html will be rendered correctly

Hello World!

Note: ng-bind-html functionality will validate Html and log errors in the console window. To disable this validation, ex.: for production environments, use the following code:

<div ng-bind-html=”skipValidation(variable)”></div>

In the controller add:

$sce service in the controller arguments:
app.controller(‘myCtrl’, function($scope, $sce){

$scope.skipValidation = function(value){ $sce.trustAsHtml(value);
};

}

--

--

Bashar Ayyash

Front End Developer, I’m confident that Vue.js is as powerful as React, but way more flexible and a lot easier to learn