How to properly escape special characters using ngSanitize?

JRulz picture JRulz · Apr 1, 2014 · Viewed 15.9k times · Source

I want to let user enter special characters such as "&" and then convert those to correct html when page is submitted. ex "&" => "&amp" I have read the examples and found ng-bind-html and $sce.

It seems ng-bind-html is useless for my need as it will only show html text sent from controller properly converted in the view. ex: it will show "&amp" as "&" to the user. So what I'm doing is converting the characters using "$sce" at the controller before sending it to server. Ex:

var accountName = $sce($scope.accountName);

Is this the correct way to do this? Or is there a straight forward way to bind the view to pass sanitized text to the controller, just like ng-bind-html but in a two-way binding? I'm using Angular 1.2.4.

Answer

JRulz picture JRulz · Apr 2, 2014

Based on references and examples found under ngSanitize module included in angular-sanitize.js, the ideal way to parse input into properly escaped html string, is by using $sanitize component. Ex:

var accountName = $sanitize( $scope.accountName );

For this, it is required to include ngSanitize in the angular app module:

var myapp = angular.module('myapp',['ngSanitize']);

and included $sanitize in the controller where $sanitize is used:

myapp.controller('myctrl', [ "$scope", "$sanitize", function ( $scope, $sanitize) {
  // code goes here

  var accountName = $sanitize( $scope.accountName );

  // further processing after sanitizing html input goes here
  }
}]);

$sce is a service in angular that provides Strict Contextual Escaping, in which angular requires binding in certain contexts with values that are safe to be used. Further information can be found in angular documentation.