1 回答

TA貢獻1872條經驗 獲得超4個贊
第一個要注意的是這些函數的調用順序:
復制代碼 代碼如下:
// 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
這個例子清晰的顯示出了ng在link之前編譯所有的指令,然后link要又分為了pre-link與post-link階段.
注意下,compile與pre-link的執行順序是依次執行的,但是post-link正好相反.
所以上面已經明確標識出了不同的階段,但是compile與pre-link有什么區別呢,都是相同的執行順序,為什么還要分成兩個不同的函數呢?
DOM
為了挖的更深一點,讓我們簡單的修改一下上面的代碼,它也會在各個函數里打印參數列表中的element變量
復制代碼 代碼如下:
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標記基本沒別的改變.
這個應該能夠加深我們對于這些函數上下文的理解.
- 1 回答
- 0 關注
- 630 瀏覽
添加回答
舉報