在angularJs應(yīng)用啟動之前,它們是以HTML文本形式存在文本編輯器當(dāng)中君珠。應(yīng)用啟動會進行編譯和鏈接寝志,作用域會同HTML進行綁定。
在編譯的階段葛躏,angularJs會遍歷整個的文檔并根據(jù)JavaScript中指令定義來處理頁面上什么的指令澈段。通常情況下,如果設(shè)置了compile函數(shù)舰攒,說明我們希望在指令和實時數(shù)據(jù)被放到DOM中之前,進行DOM操作悔醋,在這個函數(shù)中進行諸如添加和刪除節(jié)點等DOM操作是安全的摩窃。
本質(zhì)上,當(dāng)我們設(shè)置了link選項,實際上是創(chuàng)建了一個postLink() 鏈接函數(shù)猾愿,以便compile() 函數(shù)可以定義鏈接函數(shù)鹦聪。編譯函數(shù)compile負(fù)責(zé)對模板DOM進行轉(zhuǎn)換。鏈接函數(shù)link負(fù)責(zé)將作用域和DOM進行鏈接蒂秘。
//demo1 最簡單的指令創(chuàng)建
ui.directive('header', function () {
return {
restrict: 'AE',
link: function (scope, element, attrs) {
}
}
});
//demo2 等價于demo1
ui.directive('header', function () {
return {
restrict: 'AE',
compile: function (element, attrs, transclude) {
return : function(scope, element, attrs){
}
}
}
});
//demo3 等價于demo1
ui.directive('header', function () {
return {
restrict: 'AE',
compile: function (element, attrs, transclude) {
return {
pre: function(scope, element, attrs){},
post: function(scope, element, attrs){}
}
}
}
});
如果同時設(shè)置了compile與link泽本,那么會把compile所返回的函數(shù)當(dāng)作鏈接函數(shù),而link選項本身則會被忽略姻僧。