1 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
第一個(gè)要注意的是這些函數(shù)的調(diào)用順序:
復(fù)制代碼 代碼如下:
// COMPILE PHASE
// levelOne: compile function is called
// levelTwo: compile function is called
// levelThree: compile function is called
// PRE-LINK PHASE
// levelOne: pre link function is called
// levelTwo: pre link function is called
// levelThree: pre link function is called
// POST-LINK PHASE (Notice the reverse order)
// levelThree: post link function is called
// levelTwo: post link function is called
// levelOne: post link function is called
這個(gè)例子清晰的顯示出了ng在link之前編譯所有的指令,然后link要又分為了pre-link與post-link階段.
注意下,compile與pre-link的執(zhí)行順序是依次執(zhí)行的,但是post-link正好相反.
所以上面已經(jīng)明確標(biāo)識(shí)出了不同的階段,但是compile與pre-link有什么區(qū)別呢,都是相同的執(zhí)行順序,為什么還要分成兩個(gè)不同的函數(shù)呢?
DOM
為了挖的更深一點(diǎn),讓我們簡單的修改一下上面的代碼,它也會(huì)在各個(gè)函數(shù)里打印參數(shù)列表中的element變量
復(fù)制代碼 代碼如下:
var app = angular.module('plunker', []);
function createDirective(name){
return function(){
return {
restrict: 'E',
compile: function(tElem, tAttrs){
console.log(name + ': compile => ' + tElem.html());
return {
pre: function(scope, iElem, iAttrs){
console.log(name + ': pre link => ' + iElem.html());
},
post: function(scope, iElem, iAttrs){
console.log(name + ': post link => ' + iElem.html());
}
}
}
}
}
}
app.directive('levelOne', createDirective('levelOne'));
app.directive('levelTwo', createDirective('levelTwo'));
app.directive('levelThree', createDirective('levelThree'));
注意下console.log里的輸出,除了輸出原始的html標(biāo)記基本沒別的改變.
這個(gè)應(yīng)該能夠加深我們對于這些函數(shù)上下文的理解.
- 1 回答
- 0 關(guān)注
- 684 瀏覽
添加回答
舉報(bào)