angularjs 可以加入html標籤方法------ng-bind-html的用法總結

來源:互聯網
上載者:User

標籤:

本篇主要講解angular中的$sanitize這個服務.此服務依賴於ngSanitize模組.(這個模組需要載入angular-sanitize.js外掛程式)

要學習這個服務,先要瞭解另一個指令: ng-bing-html.

顧名思義,ng-bind-html和ng-bind的區別就是,ng-bind把值作為字串,和元素的內容進行綁定,但是ng-bind-html把值作為html,和元素的html進行綁定.相當於jq裡面的.text()和.html().

但是,出於安全考慮,如果我們直接使用ng-bind-html是會報錯的,ng-bind-html後面的內容必須經過一定的處理.

處理的方式有兩種,一種是使用$sce服務,另一種就是使用$sanitize服務.$sce服務怎麼用,在以後的文章中會獨立講解,這篇主要講解$sanitize服務.

$sanitize會根絕一個白名單來淨化html標籤.這樣,不安全的內容就不會被返回. 白名單是根據$compileProvider的aHrefSanitizationWhitelist和imgSrcSanitizationWhitelist函數得到的. 

看一個栗子:

<!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="stylesheet" /></head><body><div class="container">    <table class="table table-bordered" ng-controller="ctrl">        <thead>        </thead>        <tbody>        <tr>            <td>ng-bind-html</td>            <td>使用內建的$sanitize <br/>(不需要出現在js裡,只要模型添加了ngSanitize模組, <br/>然後使用ng-bind-html,它的值就自動通過$sanitize編譯)</td>            <td><div ng-bind-html="myHtml"></div></td>        </tr>        <tr>            <td>ng-bind-html</td>            <td>使用$sce的trustAsHtml方法編譯<br/>(以後會細講$sce服務,這裡不是重點)</td>            <td><div ng-bind-html="trustHtml"></div></td>        </tr>        <tr>            <td>ng-bind</td>            <td>不編譯</td>            <td><div ng-bind="myHtml"></div></td>        </tr>        </tbody>    </table></div></body></html>

angularjs 可以加入html標籤方法------ng-bind-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.