前言
在為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>總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答