5、AngularJS 直接绑定显示html ($sce、$sanitize服务)

1、直接使用$sce服务(angularjs中:$sce.trustAsHtml($scope.snippet)。html:ng-bind-html="snippet")

以下代码输出:5、AngularJS 直接绑定显示html ($sce、$sanitize服务)

 <div ng-bind-html="snippet"></div>

 <script>
  angular.module('sanitizeExample', [])
  .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
        //测试用字符串
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
        //$sce 服务trustAsHtml 进行编译
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
}]);
</script>

2、使用angular-sanitize.js 模块中的$sanitize服务,信任字符串,直接显示html

以下代码输出:5、AngularJS 直接绑定显示html ($sce、$sanitize服务)

 <div ng-bind-html="snippet"></div>

 <script>
  angular.module('sanitizeExample', ['ngSanitize'])
  .controller('ExampleController', ['$scope', function($scope) {
        //测试用字符串
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
}]);
</script>

3、整体demo代码:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body ng-app="sanitizeExample">
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Directive</td>
<td>How</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="bind-html-with-sanitize">
<td>ng-bind-html</td>
<td>Automatically uses $sanitize</td>
<td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
<td><div ng-bind-html="snippet"></div></td>
</tr>
<tr id="bind-html-with-trust">
<td>ng-bind-html</td>
<td>Bypass $sanitize by explicitly trusting the dangerous value</td>
<td>
<pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;&lt;/div&gt;</pre>
</td>
<td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
</tr>
<tr id="bind-default">
<td>ng-bind</td>
<td>Automatically escapes</td>
<td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</div>
<script>
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
}]);
</script>
</body>
//修改为本地angular.js 相对地址
<script src="angular.min.js" type="text/javascript"></script>
<script src="angular-sanitize.js" type="text/javascript"></script>
</html>
上一篇:理解 JavaScript 回调函数并使用


下一篇:【MySQL】mysql在Windows下使用mysqldump命令备份数据库