Angular.js資料繫結時自動轉義html標籤及內容

來源:互聯網
上載者:User

標籤:字串   開啟   依賴   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標籤及內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.