今天研究指令嵌套時,發現子指令的link函數先於父指令的link函數執行。
這樣和預想的順序不一樣。
也就是說,如果子指令的某個scope變量依賴於父指令傳來的參數時,可能一直是undefinded比如:
APP.directive("子指令", function () {
return {
scope: {
變量A:"=父指令的參數"
},
restrict: 'A',
replace: false,
link: function (scope, elem, attr) {
scope.變量B=scope.變量A;//變量量B其實永遠是undefinded,因為Link先於父指令的Link執行,
//導致此時子指令還沒有得到父指令傳來的參數值。
}
}
});
怎么辦呢?用scope.watch解決吧。
APP.directive("子指令", function () {
return {
scope: {
變量A:"=父指令的參數"
},
restrict: 'A',
replace: false,
link: function (scope, elem, attr) {
scope.$watch("變量A",function(){
scope.變量B=scope.變量A;
})
}
}
});