詳解Angular.js數(shù)據(jù)綁定時自動轉(zhuǎn)義html標(biāo)簽及內(nèi)容
angularJS在進(jìn)行數(shù)據(jù)綁定時默認(rèn)是以字符串的形式數(shù)據(jù),也就是對你數(shù)據(jù)中的html標(biāo)簽不進(jìn)行轉(zhuǎn)義照單全收,這樣提高了安全性,防止html標(biāo)簽的注入攻擊,但有時候需要,特別是從數(shù)據(jù)庫讀取帶格式的文本時,無法正常的顯示在頁面中。
而要對html進(jìn)行轉(zhuǎn)義,則需要在數(shù)據(jù)綁定的html標(biāo)簽中使用ng-bind-html屬性,該屬性依賴與$sanitize,也就是需要引入angular-sanitize.js文件,并在module定義時注入該服務(wù)ngSanitize。比如:
html:
<span ng-controller = "myCtr" ng-bind-html = "htmlStr"></span>
javascript:
function myCtr($scope){ $scope.htmlStr = '<p style="color:white;background:#f60;"></p>'; };
這樣可以實(shí)現(xiàn)html轉(zhuǎn)義,但是有個問題是style這種標(biāo)簽會被angularJS認(rèn)為是不安全的所以統(tǒng)統(tǒng)自動過濾掉,而為了保留這些就需要開啟非安全模式。
如何讓自動加載的數(shù)據(jù)轉(zhuǎn)義html標(biāo)簽?zāi)???shí)際上還有一種綁定方式:
html:
<div ng-repeat = "article in articles"> <div class="panel-heading"> <h4><b>{{article.title}}</b></h4> </div> <div class="panel-body"> <article id="word-display" ng-bind-html="article.content | trustHtml"> </article> </div> </div>
javascript:
success(function(data){ $scope.articles = data; }); myApp.filter('trustHtml',function($sce){ return function(input){ return $sce.trustAsHtml(input); } });
其中$sce是angularJS自帶的安全處理模塊,$sce.trustAsHtml(input)方法便是將數(shù)據(jù)內(nèi)容以html的形式進(jìn)行解析并返回。將此過濾器添加到ng-bind-html所綁定的數(shù)據(jù)中,便實(shí)現(xiàn)了在數(shù)據(jù)加載時對與html標(biāo)簽的自動轉(zhuǎn)義。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- AngularJs定時器$interval 和 $timeout詳解
- Angular.js中定時器循環(huán)的3種方法總結(jié)
- AngularJS定時器的使用與移除操作方法【interval與timeout】
- Angularjs 雙向綁定時字符串的轉(zhuǎn)換成數(shù)字類型的問題
- angularjs定時任務(wù)的設(shè)置與清除示例
- AngularJS實(shí)現(xiàn)頁面定時刷新
- angular2倒計時組件使用詳解
- ionic+AngularJs實(shí)現(xiàn)獲取驗(yàn)證碼倒計時按鈕
- AngularJS 支付倒計時功能實(shí)現(xiàn)思路
- Angular實(shí)現(xiàn)的簡單定時器功能示例
相關(guān)文章
AngularJS基于ngInfiniteScroll實(shí)現(xiàn)下拉滾動加載的方法
這篇文章主要介紹了AngularJS基于ngInfiniteScroll實(shí)現(xiàn)下拉滾動加載的方法,結(jié)合實(shí)例形式分析AngularJS下拉滾動插件ngInfiniteScroll的下載、功能、屬性及相關(guān)使用方法,需要的朋友可以參考下2016-12-12AngularJS使用ngMessages進(jìn)行表單驗(yàn)證
這篇文章主要介紹了AngularJS使用ngMessages進(jìn)行表單驗(yàn)證的相關(guān)資料,需要的朋友可以參考下2015-12-12Angular實(shí)現(xiàn)圖片裁剪工具ngImgCrop實(shí)踐
本篇文章主要介紹了Angular實(shí)現(xiàn)圖片裁剪工具ngImgCrop實(shí)踐,具有一定的參考價值,有興趣的可以了解一下2017-08-08