這篇主要介紹指令中的templateUrl屬性:css
templateUrl屬性值是一個url路徑,路徑指向一個html模板,html模板會填充(或替換)指令內容:html
好比上一篇文章裏的案例,咱們把原來的template屬性改用爲templateUrl屬性:git
方法一:github
html:app
<!DOCTYPE html> <html ng-app = 'dirAppModule'> <head> <title>20.2 指令(templateUrl)</title> <meta charset="utf-8"> <script src="angular.js"></script> <script src="script.js"></script> <style type="text/css"> *{ font-family:'MICROSOFT YAHEI'; font-size:12px } h3 { color: #CB2027; } </style> </head> <body> <div> <cd-hello></cd-hello> <div cd-hello></div> <div class="cd-hello"></div> </div> </body> </html>
js:異步
var dirAppModule = angular.module('dirAppModule',[]); dirAppModule.directive('cdHello',function(){ return { restrict:'EAC', replace:true, templateUrl:'hello.html' } });
hello.html:函數
<h3>hi,code_bunny</h3>
這樣獲得的結果和使用template:<h3>hi,code_bunny</h3>獲得的結果是一致的.url
*以這種方式使用templateUrl屬性必須在環境中運行,本地文件是不行的.spa
方法二: rest
上面這種方式加載模板,在模板文件比較大,加載須要必定時間的狀況下,用戶可能先看到標識符,等待模板加載完後纔看到內容.若是要避免這種狀況,能夠使用如下方法:
html:
<!DOCTYPE html> <html ng-app="dirAppModule"> <head> <title>20.3指令</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script type="text/ng-template" id="hello.html"> <h3>hi,code_bunny</h3> </script> <script src="script.js"></script> </head> <body> <cd-hello></cd-hello> <div cd-hello></div> <div class="cd-hello"></div> </body> </html>
js:
/*20.3 指令 */ var dirAppModule = angular.module('dirAppModule',[]); dirAppModule.directive('cdHello',function(){ return { restrict:'EAC', templateUrl:'hello.html', replace:true } });
直接在頁面裏添加一個script標籤,script的type屬性爲:text/ng-template, script的id屬性值本身定義,templateUrl的值就是這個script標籤的id屬性值,好比這個例子中的hello.html
注意這個script標籤是不會發送http請求的.
方法三:
html:
<!DOCTYPE html> <html ng-app="dirAppModule"> <head> <title>20.4指令</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </head> <body> <cd-hello></cd-hello> <div cd-hello></div> <div class="cd-hello"></div> </body> </html>
js:
/*20.4 指令 */ var appModule = angular.module('dirAppModule', []); appModule.run(function($templateCache){ $templateCache.put('hello.html','<h3>hi,code_bunny</h3>') }); appModule.directive('cdHello',function(){ return { restrict:'EAC', templateUrl:'hello.html', replace:true } });
說明: 經過angular建立的模塊,都有一個run方法,接受一個函數做爲參數.該函數會被執行.
$templateCache是angular內置的一個服務,它的put方法用於存放模板.它接受兩個參數,第一個參數爲模板的名字,也就是templateUrl的值,這裏就是hello.html,第二個參數就是html字符串,也就是模板的內容.
這種方法經常使用於模板內容是經過$http異步獲取的.而後將模板放入$templateCache中以便後面使用.
完整代碼:https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/20.2%20%E6%8C%87%E4%BB%A4
https://github.com/OOP-Code-Bunny/angular/blob/master/OREILLY/20.3%20%E6%8C%87%E4%BB%A4.html
https://github.com/OOP-Code-Bunny/angular/blob/master/OREILLY/20.4%20%E6%8C%87%E4%BB%A4.html
https://github.com/OOP-Code-Bunny/angular/blob/master/OREILLY/script.js