angularJS1筆記-(17)-ng-bind-html指令

來源:互聯網
上載者:User

標籤:bin   csharp   htm   lan   引入   環境   har   作用   sha   

angular不推薦大家在綁定資料的時候綁定html,但是如果你非要這麼幹也並不是不可以的。舉個例子:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>指令</title></head><body ng-app ng-init="username=‘<h1>shit</h1>‘"><!--ng-bind指令在綁定的值包含html時會轉義,為了安全(跨站指令碼攻擊)--><strong ng-bind-html="username"></strong><script src="app/bower_components/angular/angular.js"></script></body></html>

  寫這樣的一段代碼在瀏覽器運行:

      會看到錯誤資訊:

  看意思是在一個安全的環境中使用了不安全的值導致的,這個時候我們需要引入angular的一個依賴包 angular-sanitize:

引入完成後我們匯入項目,然後在模組中寫明依賴:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>指令</title></head><body ng-app="myApp" ng-init="username=‘<h1>shit</h1>‘"><!--ng-bind指令在綁定的值包含html時會轉義,為了安全(跨站指令碼攻擊)--><strong ng-bind-html="username"></strong><script src="app/bower_components/angular/angular.js"></script><script src="app/bower_components/angular-sanitize/angular-sanitize.js"></script><script>    //使用自訂的模組才可以依賴別的包裡面定義模組 angular定義的預設模組沒有任何依賴    angular.module(‘myApp‘, [‘ngSanitize‘])</script></body></html>

  此時運行就可以看到正確結果ngSanitize的作用是讓html不轉義:

 

angularJS1筆記-(17)-ng-bind-html指令

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.