angular模板加載 ----ng-template


Angularjs作為mvc(或者說mvvm)框架,同樣具備模板這一基本概念。

NG加載模板的順序為 內存加載---AJAX加載。

內存加載

如果之前使用過Bootstrap 插件的ng版,即angular-ui,就會了解到這種方式的具體應用。模板本質上是字符串,把字符串直接寫入內存,加載時直接從內存獲取,速度會更快,有兩種方式顯式啟用內存加載。

  • 通過使用$templateCache service來實現
    angular.module('myApp', [])
      .controller('myCtrl', ['$scope','$templateCache', function($scope,$templateCache){
           var tmp = '<h4>lovestory</h4>'
                 + '<p>這是直接調用$templateCache服務獲取模板文件的方式</p>'
                 + '<a href="http://www.baidu.com">服務啟用templateCache方式</a>';
           $templateCache.put('lovestory.html',tmp);                
       }])
    <script type="text/ng-template" id="lovestory.html">
        <h4>lovestory</h4>
        <p>這是script標簽獲取模板文件的方式</p>
        <a href="http://www.baidu.com">標簽啟用templateCache方式</a>
    </script>

    這里需要注意,type="text/ng-template"是指明這是ng模板,id屬性是指實際使用模板時的一個引用,標簽之間的內容才是實際的模板內容。而且,需要注意,id絕對不是URL,這個script標簽絕對不會發出HTTP請求,具體討論見最后。
    實際應用模板時候,使用ID屬性,即可從內存中獲取對應數據。

    <div ng-include="'lovestory.html'" class="well"></div>

    <div ng-include="'lovestory.html'" class="well"></div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM