1. 程式人生 > >angularjs ng-bind-html的用法總結

angularjs ng-bind-html的用法總結

html標簽 白名單 href list函數 指令 app his itl tro

angular中的$sanitize服務.

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

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

顧名思義,ng-bind-html和ng-bind的區別就是,ng-bind把值作為字符串,和元素的內容進行綁定,但是ng-bind-html把值作為html,和元素的html進行綁定.相當於jq裏面的.text()和.html().

但是,出於安全考慮,如果我們直接使用ng-bind-html是會報錯的,ng-bind-html後面的內容必須經過一定的處理.

處理的方式有兩種,一種是使用$sce服務,另一種就是使用$sanitize服務.$sce

服務怎麽用,在以後的文章中會獨立講解,這篇主要講解$sanitize服務.

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

比如

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)
});

angularjs ng-bind-html的用法總結