angularjs中ng-bind-html的用法總結(jié)
本篇主要講解angular中的$sanitize這個服務(wù).此服務(wù)依賴于ngSanitize模塊.(這個模塊需要加載angular-sanitize.js插件)
要學(xué)習(xí)這個服務(wù),先要了解另一個指令: ng-bing-html.
顧名思義,ng-bind-html和ng-bind的區(qū)別就是,ng-bind把值作為字符串,和元素的內(nèi)容進行綁定,但是ng-bind-html把值作為html,和元素的html進行綁定.相當于jq里面的.text()和.html().
但是,出于安全考慮,如果我們直接使用ng-bind-html是會報錯的,ng-bind-html后面的內(nèi)容必須經(jīng)過一定的處理.
處理的方式有兩種,一種是使用$sce服務(wù),另一種就是使用$sanitize服務(wù).$sce服務(wù)怎么用,在以后的文章中會獨立講解,這篇主要講解$sanitize服務(wù).
$sanitize會根絕一個白名單來凈化html標簽.這樣,不安全的內(nèi)容就不會被返回. 白名單是根據(jù)$compileProvider的aHrefSanitizationWhitelist和imgSrcSanitizationWhitelist函數(shù)得到的.
看一個栗子:
html:
<!DOCTYPE html> <html ng-app="myApp"> <head> <title></title> <meta charset="utf-8"> <script src="../angular-1.3.2.js"></script> <script src="angular-sanitize.min.js"></script> <script src="script.js"></script> <link type="text/css" href="../bootstrap.css" rel="external nofollow" rel="stylesheet" /> </head> <body> <div class="container" ng-controller="ctrl"> <div ng-bind-html="trustHtml"></div> </div> </body> </html>
js:
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)
});
這樣,在div內(nèi)就能加載上帶有html標簽的內(nèi)容,標簽的屬性以及綁定在元素上的事件都會被保留。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Angular material主題定義自己的組件庫的配色體系
這篇文章主要介紹了使用Angular material主題定義自己的組件庫的配色體系的相關(guān)知識,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
AngularJS 獲取ng-repeat動態(tài)生成的ng-model值實例詳解
angularJs使用ng-repeat遍歷后選中某一個的方法

