Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly escape special characters using ngSanitize?

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.

like image 994
JRulz Avatar asked Dec 14 '25 13:12

JRulz


1 Answers

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.

like image 126
JRulz Avatar answered Dec 16 '25 09:12

JRulz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!