1.代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="angular.js"></script>
<script src="sanitize.js"></script>
</head>
<body>
<div ng-app="testapp" ng-controller="ctrl">
<div ng-bind-html="myHtml"></div>
<div ng-bind-html="trustHtml"></div>
</div>
<script>
var app = angular.module('testapp', ['ngSanitize']);
app.controller('ctrl',function($scope,$sce){
$scope.myHtml = "<div><button onclick='alert(123)'>test</button></div>";
$scope.trustHtml = $sce.trustAsHtml($scope.myHtml)
});
</script>
</body>
</html>
2.结果

AngularJS与ngSanitize
本文展示了一个使用AngularJS和ngSanitize模块的例子,通过代码演示了如何在AngularJS应用中安全地绑定HTML内容,避免XSS攻击。通过$sce服务的trustAsHtml方法,可以将潜在危险的HTML字符串转换为可信任的HTML内容。
827

被折叠的 条评论
为什么被折叠?



