首頁  >  文章  >  web前端  >  解析AngularJS中的ng-bind-html指令

解析AngularJS中的ng-bind-html指令

怪我咯
怪我咯原創
2017-04-30 10:55:401803瀏覽

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

前言

在為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">
 <p ng-controller="MyController">
 {{content}}
 <p ng-bind="content"></p> 
 </p>
</body>
</html>

輸出

#ng-bind-html指令

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

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

但可以透過引入下面的模組,自動偵測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">
 <p ng-controller="MyController">
 {{content}}
 <p ng-bind="content"></p> 
 <!--<p ng-bind-html="content"></p>-->
 <p ng-bind-html="content|safeHtml"></p>
 </p>
</body>
</html>

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

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