深入理解AngularJS中的ng-bind-html指令
前言
在為html標(biāo)簽綁定數(shù)據(jù)的時(shí),如果綁定的內(nèi)容是純文本,你可以使用{{}}或者ng-bind。但在為html標(biāo)簽綁定帶html標(biāo)簽的內(nèi)容的時(shí)候,angularjs為了安全考慮,不會(huì)將其渲染成html,而是將其當(dāng)做文本直接在頁面上展示。
先來看一個(gè)例子
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="js/angular.min.js"></script>
<script>
angular.module("myapp", []).controller("MyController", function ($scope) {
$scope.content = "<h1>Hello world.</h1>";
$scope.txt = "Hello txt world";
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="MyController">
{{content}}
<div ng-bind="content"></div>
</div>
</body>
</html>
輸出

ng-bind-html指令
<div ng-bind-html="content"></div>
這時(shí)就會(huì)出現(xiàn)安全的錯(cuò)誤,如圖:

但可以通過引入下面的模塊,自動(dòng)檢測(cè)html的內(nèi)容是否安全
<script src="http://apps.bdimg.com/libs/angular.js/1.5.0-beta.0/angular-sanitize.min.js"></script>
<script>
angular.module("myapp", ["ngSanitize"]).controller("MyController", function ($scope) {
$scope.content = "<h1>Hello world.</h1>";
$scope.txt = "Hello txt world";
});
</script>
這時(shí)刷新預(yù)覽

所以
ng-bind-html 指令是通一個(gè)安全的方式將內(nèi)容綁定到 HTML 元素上。
當(dāng)你想讓 AngularJS 在你的應(yīng)用中寫入 HTML,你就需要去檢測(cè)一些危險(xiǎn)代碼。通過在應(yīng)用中引入 "angular-santize.js" 模塊,使用 ngSanitize 函數(shù)來檢測(cè)代碼的安全性。 in your application you can do so by running the HTML code through the ngSanitize function.
另外一種處理方式
通過自定義過濾器,將帶html標(biāo)簽的內(nèi)容都當(dāng)成安全的進(jìn)行處理。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="js/angular.min.js"></script>
<!--<script src="http://apps.bdimg.com/libs/angular.js/1.5.0-beta.0/angular-sanitize.min.js"></script>-->
<script>
angular.module("myapp", []).controller("MyController", function ($scope) {
$scope.content = "<h1>Hello world.</h1>";
$scope.txt = "Hello txt world";
}).filter("safeHtml", function ($sce) {
return function (input) {
//在這里可以對(duì)加載html渲染后進(jìn)行特別處理。
return $sce.trustAsHtml(input);
};
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="MyController">
{{content}}
<div ng-bind="content"></div>
<!--<div ng-bind-html="content"></div>-->
<div ng-bind-html="content|safeHtml"></div>
</div>
</body>
</html>
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
angular ng-click防止重復(fù)提交實(shí)例
本篇文章主要介紹了angular ng-click防止重復(fù)提交實(shí)例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
AngularJS入門教程之與服務(wù)器(Ajax)交互操作示例【附完整demo源碼下載】
這篇文章主要介紹了AngularJS與服務(wù)器Ajax交互操作的方法,可實(shí)現(xiàn)post傳輸數(shù)據(jù)的功能,并附帶完整的demo源碼供讀者下載參考,源碼中還包含了前面章節(jié)的示例文件,需要的朋友可以參考下2016-11-11

