這篇主要介紹指令中的templateUrl屬性:
templateUrl屬性值是一個url路徑,路徑指向一個html模板,html模板會填充(或替換)指令內容:
比如上一篇文章里的案例,我們把原來的template屬性改用為templateUrl屬性:
方法一:
html:
<!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>得到的結果是一致的.
*以這種方式使用templateUrl屬性必須在環境中運行,本地文件是不行的.
方法二:
上面這種方式加載模板,在模板文件比較大,加載需要一定時間的情況下,用戶可能先看到標識符,等待模板加載完后才看到內容.如果要避免這種情況,可以使用以下方法:
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