前言
在為html標(biāo)簽綁定數(shù)據(jù)的時(shí),如果綁定的內(nèi)容是純文本,你可以使用{{}}或者ng-bind。但在為html標(biāo)簽綁定帶html標(biāo)簽的內(nèi)容的時(shí)候,angularjs為了安全考慮,不會(huì)將其渲染成html,而是將其當(dāng)做文本直接在頁(yè)面上展示。
先來(lái)看一個(gè)例子
!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 /body /html
輸出
ng-bind-html指令
p ng-bind-html= content /p
這時(shí)就會(huì)出現(xiàn)安全的錯(cuò)誤,如圖:
但可以通過(guò)引入下面的模塊,自動(dòng)檢測(cè)html的內(nèi)容是否安全
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
這時(shí)刷新預(yù)覽
所以
ng-bind-html 指令是通一個(gè)安全的方式將內(nèi)容綁定到 HTML 元素上。
當(dāng)你想讓 AngularJS 在你的應(yīng)用中寫(xiě)入 HTML,你就需要去檢測(cè)一些危險(xiǎn)代碼。通過(guò)在應(yīng)用中引入 angular-santize.js 模塊,使用 ngSanitize 函數(shù)來(lái)檢測(cè)代碼的安全性。 in your application you can do so by running the HTML code through the ngSanitize function.
另外一種處理方式
通過(guò)自定義過(guò)濾器,將帶html標(biāo)簽的內(nèi)容都當(dāng)成安全的進(jìn)行處理。
!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) { //在這里可以對(duì)加載html渲染后進(jìn)行特別處理。 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 /body /html
以上就是解析AngularJS中的ng-bind-html指令的詳細(xì)內(nèi)容,html教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答