Angularjs 从用户填写的表单中清理或转义html标记
我使用html制作表单,并使用angularjs将数据发布到后端。我想在发布到后端之前转义html标记。我该怎么做 例如,如果用户发布如下内容Angularjs 从用户填写的表单中清理或转义html标记,angularjs,Angularjs,我使用html制作表单,并使用angularjs将数据发布到后端。我想在发布到后端之前转义html标记。我该怎么做 例如,如果用户发布如下内容 <p> hello world </p> ngSanitize应该可以做到这一点。请看 这里有一种从客户端实现的方法 var-app=angular.module('app',[]); app.controller('myCtrl',['$scope',函数($scope){ $scope.htmlText=“让我们来看看””;
<p> hello world </p>
ngSanitize应该可以做到这一点。请看 这里有一种从客户端实现的方法 var-app=angular.module('app',[]); app.controller('myCtrl',['$scope',函数($scope){
$scope.htmlText=“让我们来看看””;
$scope.htmlEncode=函数(){
var safeString=$('').text($scope.htmlText.html();
//如果没有jquery,请使用以下命令
//对于其他html特殊字符,safeString=$scope.htmlText.replace(“”,);//依此类推。
警报(安全字符串);
};
}]);
请参见(自回答后,问题已更新到不同的区域)
在服务器端使用以清理用户输入
不建议在客户端使用任何卫生工具,因为恶意用户可以修改脚本以忽略它们 对于这种类型的任务,你不应该信任客户端(JS)。我想在发送到后端时转义字符串。我不确定你想发布什么。我假设您希望在输入字段中使用html,如果是这样的话,最好是在服务器端完成。如果我想在客户端做。如何操作?在自定义表单验证程序中使用$sanitize。
<p> hello world </p>
$scope.htmlText = "<p> Let's see</p>";
$scope.htmlEncode = function(){
var safeString = $('<div>').text($scope.htmlText).html();
// if you don't have jquery the use the following
//safeString = $scope.htmlText.replace('<', '<').replace('>', '>');//and so on for other html special characters.
alert(safeString);
};
}]);