[英]How to make the child link directive function to run before parent controller?
[英]How to call a parent directive link function from a child directive's link function
我有兩個帶有link
功能的指令,A directiveA
和B directiveB
。 如何從directiveB
調用屬於directiveA
A的函數?
到目前為止,我設置代碼的方式是:
angular.module('myApp').directive('directiveA', function () {
return {
templateUrl: 'directiveA.html',
link: function (scope) {
scope.directiveAAlert = function () {
alert('This is A');
}
}
}
});
angular.module('myApp').directive('directiveB', function () {
return {
scope: {
onButtonClicked: '='
}
templateUrl: 'directiveB.html',
link: function (scope) {
scope.showAlert = function () {
scope.onButtonClicked();
}
}
}
});
在directiveA.html
:
<directive-b onButtonClicked='directiveAAlert'></directive-b>
在directiveB.html
:
<button ng-click='showAlert()'></button>
但是,當我單擊按鈕時,出現一個錯誤,提示TypeError: scope.onLogInButtonClicked is not a function at Scope.link.scope.showAlert
。
如何簡單地從child指令定義並調用相同的函數?
您需要使用指令的require
選項,您可以在其中提及另一個指令在同一元素上,或者它可能是我的父母在指令API的require
屬性中使用^
。 當您使用require: ^parentDirective
將使您能夠訪問需要鏈接功能的childDirective
中的parentDirective
控制器。
另外,您需要更正模板html,模板html的屬性應為-
通過替換其cammelcase大小寫分隔。
directiveA.html:
<directive-b on-button-clicked='directiveAAlert()'></directive-b>
directiveB.html
<button ng-click='showAlert()'></button>
碼
angular.module('myApp').directive('directiveA', function () {
return {
templateUrl: 'directiveA.html',
link: function (scope) {
//code here
},
controller: function($scope){
scope.directiveAAlert = function () {
alert('This is A');
}
}
}
});
angular.module('myApp').directive('directiveB', function () {
return {
scope: {
onButtonClicked: '='
},
require: '^directiveA',
templateUrl: 'directiveB.html',
link: function (scope,element,attrs, ctrl) {
scope.showAlert = function () {
ctrl.onButtonClicked(); //ctrl has access to the directive a controller.
}
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.