如何使用ngSanitize正确转义特殊字符?

JRu*_*ulz 3 html5 special-characters angularjs angularjs-directive ngsanitize

我想让用户输入特殊字符,例如"&",然后在提交页面时将它们转换为正确的html.ex"&"=>"&"我已经阅读了这些例子并找到了ng-bind-html$ sce.

似乎ng-bind-html对我的需求毫无用处,因为它只会显示从视图中正确转换的控制器发送的html文本.例如:它会向用户显示"&"为"&".所以我正在做的是在控制器上使用"$ sce"转换字符,然后再将它发送到服务器.例如:

var accountName = $sce($scope.accountName);
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?或者是否有一种直接的方式来绑定视图以将已清理的文本传递给控制器​​,就像ng-bind-html但是在双向绑定中?我正在使用Angular 1.2.4.

JRu*_*ulz 7

基于angular-sanitize.js中包含的ngSanitize模块下的参考和示例,将输入解析为正确转义的html字符串的理想方法是使用$ sanitize组件.例如:

var accountName = $sanitize( $scope.accountName );
Run Code Online (Sandbox Code Playgroud)

为此,需要在角度应用程序模块中包含ngSanitize:

var myapp = angular.module('myapp',['ngSanitize']);
Run Code Online (Sandbox Code Playgroud)

并在使用$ sanitize的控制器中包含$ sanitize:

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

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

  // further processing after sanitizing html input goes here
  }
}]);
Run Code Online (Sandbox Code Playgroud)

$ sce是一种角度服务,提供Strict Contextual Escaping,其中angular需要在某些上下文中绑定可安全使用的值.更多信息可以在角度文档中找到.