詳解Angular.js數(shù)據(jù)綁定時自動轉義html標簽及內(nèi)容
angularJS在進行數(shù)據(jù)綁定時默認是以字符串的形式數(shù)據(jù),也就是對你數(shù)據(jù)中的html標簽不進行轉義照單全收,這樣提高了安全性,防止html標簽的注入攻擊,但有時候需要,特別是從數(shù)據(jù)庫讀取帶格式的文本時,無法正常的顯示在頁面中。
而要對html進行轉義,則需要在數(shù)據(jù)綁定的html標簽中使用ng-bind-html屬性,該屬性依賴與$sanitize,也就是需要引入angular-sanitize.js文件,并在module定義時注入該服務ngSanitize。比如:
html:
<span ng-controller = "myCtr" ng-bind-html = "htmlStr"></span>
javascript:
function myCtr($scope){ $scope.htmlStr = '<p style="color:white;background:#f60;"></p>'; };
這樣可以實現(xiàn)html轉義,但是有個問題是style這種標簽會被angularJS認為是不安全的所以統(tǒng)統(tǒng)自動過濾掉,而為了保留這些就需要開啟非安全模式。
如何讓自動加載的數(shù)據(jù)轉義html標簽呢?實際上還有一種綁定方式:
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的形式進行解析并返回。將此過濾器添加到ng-bind-html所綁定的數(shù)據(jù)中,便實現(xiàn)了在數(shù)據(jù)加載時對與html標簽的自動轉義。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
AngularJS基于ngInfiniteScroll實現(xiàn)下拉滾動加載的方法
這篇文章主要介紹了AngularJS基于ngInfiniteScroll實現(xiàn)下拉滾動加載的方法,結合實例形式分析AngularJS下拉滾動插件ngInfiniteScroll的下載、功能、屬性及相關使用方法,需要的朋友可以參考下2016-12-12Angular實現(xiàn)圖片裁剪工具ngImgCrop實踐
本篇文章主要介紹了Angular實現(xiàn)圖片裁剪工具ngImgCrop實踐,具有一定的參考價值,有興趣的可以了解一下2017-08-08