angularjs ng-bind-html的用法總結

 

angular中的$sanitize服務.html

此服務依賴於ngSanitize模塊.(這個模塊須要加載angular-sanitize.js插件)安全

要學習這個服務,先要了解另外一個指令: ng-bing-html.app

顧名思義,ng-bind-html和ng-bind的區別就是,ng-bind把值做爲字符串,和元素的內容進行綁定,可是ng-bind-html把值做爲html,和元素的html進行綁定.至關於jq裏面的.text()和.html().ide

可是,出於安全考慮,若是咱們直接使用ng-bind-html是會報錯的,ng-bind-html後面的內容必須通過必定的處理.函數

處理的方式有兩種,一種是使用$sce服務,另外一種就是使用$sanitize服務.$sce服務怎麼用,在之後的文章中會獨立講解,這篇主要講解$sanitize服務.post

$sanitize會根絕一個白名單來淨化html標籤.這樣,不安全的內容就不會被返回. 白名單是根據$compileProvider的aHrefSanitizationWhitelist和imgSrcSanitizationWhitelist函數獲得的. 學習

好比this

var app =angular.module(‘myApp‘,[‘ngSanitize‘]);
app.controller(‘ctrl‘,function($scope,$sce){
    $scope.myHtml = ‘<p style="color:blue">an html\n‘ +
    ‘<em onclick="this.textContent=\‘code_bunny\‘">click here</em>\n‘ +
    ‘snippet</p>‘;
    $scope.trustHtml = $sce.trustAsHtml($scope.myHtml)
});
相關文章
相關標籤/搜索