02directive——Angularjs的創建指令方法
restrict 值分類:
- E 作爲元素名使用,例如:
<hello></hello>
- A 作爲屬性使用(默認),例如:
<div hello></div>
- C 作爲類名使用 , 例如:
<div class="hello"></div>
- M 作爲註釋使用, 例如:
<!--directive:hello-->
directive的templateUrl屬性
通常我們這樣寫,template,但是如果模板裏面東西很多,我們就需要獨立出來一個html文件,
myApp.directive('hello',function(){
return{
restrict : 'AEMC', //- A 作爲屬性使用(默認),例如:`<div hello></div>`
template : '<div>Hello everyone, I am bangbang!</div>',
replace : true
}
})
用templateUrl屬性獨立出html文件,注意:如果用longDirective命名,引用的時候用<long-directive></long-directive>
,要不然就用純小寫字母
myApp.directive('longDirective',function(){
return {
restrict : 'AEMC', //- E 作爲元素名使用,例如:`<hello></hello>`
templateUrl : 'tpls/long.html',
replace : true
}
})
$templateCache(緩存模板方法)
通過angular創建的模塊,都有一個run方法,注射器在加載完成所有模塊的時候,該方法使用一次。接受一個函數作爲參數.該函數會被執行.
myApp.run(function($templateCache){
// $templateCache.put('tpls/cache.html','<div>hello everyone!!!!</div>')
$templateCache.put('cache.html','<p>我是緩存的模板</p>')
});
myApp.directive('cacheDirective',function($templateCache){
return{
restrict : 'AECM',
template : $templateCache.get('cache.html'),
replace : true
}
})
transclude屬性的使用(讓創建的標籤裏面的內容不被替換)
下面代碼讓html頁面中的<no-Replace>希望我不被替換掉</no-Replace>
裏面的內容不會被替換
myApp.directive("noReplace",function(){
return {
restrict : 'AECM',
template : "<div>Hello everyone,I am noReplace!</div><div ng-transclude></div>",
transclude : true
}
})
compile與link
Angularjs的運行流程如下所示:
- compile函數用來對模板自身進行轉換,link函數負責在模型和視圖之間進行動態關聯;
- 作用域在鏈接階段纔會被綁定到編譯之後的link函數上;
- compile函數僅僅在便一階段運行一次,而對於指令的每個實例,link函數都會執行一次;
- compile可以返回preLink和postLink函數,而link函數只會返回postLink函數;
- 如果需要修改DOM結構,應該在postLink中來做這件事,而如果preLink中做這件事情會導致失誤,大所屬時候我們只需要編寫link函數即可;
myApp.directive('cpl',function(){
return {
restrict : 'AECM',
template : '<div>Hello bangbang</div>',
replace : true,
compile : function(){ //用來對模板自身進行轉換
},
link : function(){ //用來操作DOM和綁定事件監聽器
}
}
})
githu源碼:02directive —— 自定義指令的方法