本篇主要讲解 angular 中的 $sanitize 这个服务. 此服务依赖于 ngSanitize 模块.(这个模块需要加载 angular-sanitize.js 插件)
要学习这个服务, 先要了解另一个指令: ng-bing-html.
顾名思义, ng-bind-html 和 ng-bind 的区别就是, ng-bind 把值作为字符串, 和元素的内容进行绑定, 但是 ng-bind-html 把值作为 html, 和元素的 html 进行绑定. 相当于 jq 里面的. text() 和. html().
但是, 出于安全考虑, 如果我们直接使用 ng-bind-html 是会报错的, ng-bind-html 后面的内容必须经过一定的处理.
处理的方式有两种, 一种是使用 $sce 服务, 另一种就是使用 $sanitize 服务.$sce 服务怎么用, 在以后的文章中会独立讲解, 这篇主要讲解 $sanitize 服务.
$sanitize 会根绝一个白名单来净化 html 标签. 这样, 不安全的内容就不会被返回. 白名单是根据 $compileProvider 的 aHrefSanitizationWhitelist 和 imgSrcSanitizationWhitelist 函数得到的.
看一个栗子:
html:
- <!DOCTYPE html>
- <html ng-app="myApp">
- <head>
- <title>
- </title>
- <meta charset="utf-8">
- <script src="../angular-1.3.2.js">
- </script>
- <script src="angular-sanitize.min.js">
- </script>
- <script src="script.js">
- </script>
- <link type="text/CSS" href="../bootstrap.css" rel="external nofollow"
- rel="stylesheet" />
- </head>
- <body>
- <div class="container" ng-controller="ctrl">
- <div ng-bind-html="trustHtml">
- </div>
- </div>
- </body>
- </html>
js:
- var app =angular.module('myApp',['ngSanitize']);
- app.controller('ctrl',function($scope,$sce){
- $scope.myHtml = '<p style="color:blue">an html\n' +
- '<em onclick="this.textContent=\'code_bunny\'">click here</em>\n' +
- 'snippet</p>';
- $scope.trustHtml = $sce.trustAsHtml($scope.myHtml)
- });
这样,在 div 内就能加载上带有 html 标签的内容,标签的属性以及绑定在元素上的事件都会被保留。
来源: http://www.jb51.net/article/114506.htm