標籤:字串 開啟 依賴 angularjs 添加 ash put rust word
angularJS在進行資料繫結時預設是以字串的形式資料,也就是對你資料中的html標籤不進行轉義照單全收,這樣提高了安全性,防止html標籤的注入攻擊,但有時候需要,特別是從資料庫讀取帶格式的文本時,無法正常的顯示在頁面中。
而要對html進行轉義,則需要在資料繫結的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>‘;
};
這樣可以實現html轉義,但是有個問題是style這種標籤會被angularJS認為是不安全的所以統統自動過濾掉,而為了保留這些就需要開啟非安全模式。
如何讓自動載入的資料轉義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)方法便是將資料內容以html的形式進行解析並返回。將此過濾器添加到ng-bind-html所繫結資料中,便實現了在資料載入時對與html標籤的自動轉義。
Angular.js資料繫結時自動轉義html標籤及內容