消毒ngModel

时间:2015-01-29 05:58:23

标签: angularjs

我无法确定如何通过ngModel安全地解码某些字符串。

我目前正在使用ngSanitize在视图中正确输出它,但在使用ngModel时,它会完全中断。

API响应

{
  id : 1,
  name : 'Gary's Company'
}

控制器

// Returned from the API
$scope.user = {
  id : 1,
  name : 'Gary's Company'
};

视图

<!-- Since ngModel isn't hooked up to the sanitizer, the text input field is showing the raw ASCII code. -->
<input type="text" ng-model="user.name" />

<!-- This displays "Gary's Company" correctly. The single quote gets convereted successfully. -->
<span ng-bind-html="user.name"></span>

我是在正确的轨道上还是有更好或更直接的方法?

1 个答案:

答案 0 :(得分:4)

您可以使用$sanitize服务解码控制器中的值。

$scope.user = {
  id : 1,
  name : 'Gary&#039;s Company'
};
$scope.user.name = $sanitize($scope.user.name);

$sanitize不是核心Angular包的一部分,因此您需要包含angular-sanitize.js并在ngSanitize模块上添加依赖项:

var app = angular.module('myApp', ["ngSanitize"]);