【问题标题】:How to properly escape special characters using ngSanitize?如何使用 ngSanitize 正确转义特殊字符?
【发布时间】:2014-05-11 18:05:30
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: html angularjs angularjs-directive special-characters ngsanitize


    【解决方案1】:

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

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

    为此,需要在 Angular 应用模块中包含 ngSanitize

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

    并在使用 $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
      }
    }]);
    

    $sce 是 Angular 中的一项服务,提供 严格的上下文转义,其中 Angular 需要在某些上下文中绑定可以安全使用的值。更多信息请访问angular documentation

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 2021-06-15
      • 2018-05-09
      • 2012-04-14
      • 2017-01-31
      • 1970-01-01
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多