国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

深入理解AngularJS中的ng-bind-html指令

2019-11-19 17:01:15
字體:
來源:轉載
供稿:網友

前言

在為html標簽綁定數據的時,如果綁定的內容是純文本,你可以使用{{}}或者ng-bind。但在為html標簽綁定帶html標簽的內容的時候,angularjs為了安全考慮,不會將其渲染成html,而是將其當做文本直接在頁面上展示。

先來看一個例子

<!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>

這時就會出現安全的錯誤,如圖:

但可以通過引入下面的模塊,自動檢測html的內容是否安全

 <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>

這時刷新預覽

所以

ng-bind-html 指令是通一個安全的方式將內容綁定到 HTML 元素上。

當你想讓 AngularJS 在你的應用中寫入 HTML,你就需要去檢測一些危險代碼。通過在應用中引入 "angular-santize.js" 模塊,使用 ngSanitize 函數來檢測代碼的安全性。 in your application you can do so by running the HTML code through the ngSanitize function.

另外一種處理方式

通過自定義過濾器,將帶html標簽的內容都當成安全的進行處理。

<!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) {  //在這里可以對加載html渲染后進行特別處理。  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>

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 伊通| 扎赉特旗| 龙里县| 辉县市| 华阴市| 宁强县| 台东县| 莫力| 金华市| 衡山县| 安宁市| 泸定县| 嘉鱼县| 南雄市| 万载县| 肇源县| 安达市| 河北省| 贵阳市| 盐城市| 措勤县| 惠安县| 西和县| 江阴市| 开阳县| 噶尔县| 新邵县| 松溪县| 肇东市| 汽车| 志丹县| 临沂市| 开化县| 霸州市| 蓬溪县| 芜湖市| 开原市| 郓城县| 东安县| 新邵县| 宁晋县|