首頁  >  文章  >  web前端  >  深入理解AngularJS中的ng-bind-html指令的圖文代碼詳解

深入理解AngularJS中的ng-bind-html指令的圖文代碼詳解

黄舟
黄舟原創
2017-03-28 14:58:071180瀏覽

ng-bind-html和ng-bind的差別就是,ng-bind把值當作字串,和元素的內容進行綁定,但是ng-bind-html把值作為html,和元素的html進行綁定.相當於jq裡面的.text()和.html()。文章主要給大家深入的介紹了AngularJS中ng-bind-html指令的相關資料,需要的朋友可以參考下。

##在為html標籤綁定資料的時,如果綁定的內容是純文本,你可以使用{{}}或ng-bind。綁定帶有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">
 <p ng-controller="MyController">
 {{content}}
 <p ng-bind="content"></p> 
 </p>
</body>
</html>
輸出

#ng-bind-html指令

 <p ng-bind-html="content"></p>

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

深入理解AngularJS中的ng-bind-html指令的圖文代碼詳解

但可以透過引入下面的模組,自動偵測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>
這時刷新預覽

深入理解AngularJS中的ng-bind-html指令的圖文代碼詳解

所以

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

函數

來偵測程式碼的安全性。方式深入理解AngularJS中的ng-bind-html指令的圖文代碼詳解

透過自訂過濾器

,將帶有html標籤的內容都當成安全的進行處理。 #總結

以上是深入理解AngularJS中的ng-bind-html指令的圖文代碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn