本篇主要讲解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标签的内容,标签的属性以及绑定在元素上的事件都会被保留。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
Angular8引入百度Echarts进行图表分析的实现代码
解决Angularjs异步操作后台请求用$q.all排列先后顺序问题
angular inputNumber指令输入框只能输入数字的实现
网友评论