5、AngularJS 直接绑定显示html ($sce、$sanitize服务)
1、直接使用$sce服务(angularjs中:$sce.trustAsHtml($scope.snippet)。html:ng-bind-html="snippet")
以下代码输出:
1 <div ng-bind-html="snippet"></div> 2 3 <script> 4 angular.module('sanitizeExample', []) 5 .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { 6 //测试用字符串 7 $scope.snippet = 8 '<p style="color:blue">an html\n' + 9 '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 10 'snippet</p>'; 11 //$sce 服务trustAsHtml 进行编译 12 $scope.deliberatelyTrustDangerousSnippet = function() { 13 return $sce.trustAsHtml($scope.snippet); 14 }; 15 }]); 16 </script>
2、使用angular-sanitize.js 模块中的$sanitize服务,信任字符串,直接显示html
以下代码输出:
1 <div ng-bind-html="snippet"></div> 2 3 <script> 4 angular.module('sanitizeExample', ['ngSanitize']) 5 .controller('ExampleController', ['$scope', function($scope) { 6 //测试用字符串 7 $scope.snippet = 8 '<p style="color:blue">an html\n' + 9 '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 10 'snippet</p>'; 11 }]); 12 </script>
3、整体demo代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 </head> 9 <body ng-app="sanitizeExample"> 10 <div ng-controller="ExampleController"> 11 Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> 12 <table> 13 <tr> 14 <td>Directive</td> 15 <td>How</td> 16 <td>Source</td> 17 <td>Rendered</td> 18 </tr> 19 <tr id="bind-html-with-sanitize"> 20 <td>ng-bind-html</td> 21 <td>Automatically uses $sanitize</td> 22 <td><pre><div ng-bind-html="snippet"><br/></div></pre></td> 23 <td><div ng-bind-html="snippet"></div></td> 24 </tr> 25 <tr id="bind-html-with-trust"> 26 <td>ng-bind-html</td> 27 <td>Bypass $sanitize by explicitly trusting the dangerous value</td> 28 <td> 29 <pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></pre> 30 </td> 31 <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> 32 </tr> 33 <tr id="bind-default"> 34 <td>ng-bind</td> 35 <td>Automatically escapes</td> 36 <td><pre><div ng-bind="snippet"><br/></div></pre></td> 37 <td><div ng-bind="snippet"></div></td> 38 </tr> 39 </table> 40 </div> 41 <script> 42 angular.module('sanitizeExample', ['ngSanitize']) 43 .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { 44 $scope.snippet = 45 '<p style="color:blue">an html\n' + 46 '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 47 'snippet</p>'; 48 $scope.deliberatelyTrustDangerousSnippet = function() { 49 return $sce.trustAsHtml($scope.snippet); 50 }; 51 }]); 52 </script> 53 </body> 54 //修改为本地angular.js 相对地址 55 <script src="angular.min.js" type="text/javascript"></script> 56 <script src="angular-sanitize.js" type="text/javascript"></script> 57 </html>