如何从子指令的链接函数中调用父指令的链接函数
How to call a parent directive link function from a child directive's link function
我有两个指令,directiveA
和directiveB
都具有link
函数。如何从directiveB
调用属于directiveA
的函数?
到目前为止,我的代码设置方式是:
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();
}
}
}
});
In directiveA.html
:
<directive-b onButtonClicked='directiveAAlert'></directive-b>
In directiveB.html
:
<button ng-click='showAlert()'></button>
但是当我点击按钮时,我得到一个错误说TypeError: scope.onLogInButtonClicked is not a function at Scope.link.scope.showAlert
。
如何从子指令简单地定义和调用相同的函数?
你需要使用指令的require
选项,在那里你可以提到其他指令将在同一元素上,或者它可能是我的父母在指令API的require
属性内使用^
。当你使用require: ^parentDirective
,这将给你访问parentDirective
控制器在链接函数childDirective
谁需要它。
另外,你需要纠正你的模板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.
}
}
}
});
相关文章:
- 在什么情况下需要同时使用compile&链接函数的角度
- jquery:如何链接函数
- 角度指令's链接函数未被调用
- 如何在jQuery中将链接函数分配给变量
- 如何在指令链接函数中使用从控制器传递的筛选器
- 从控制器Angularjs调用链接函数
- 从指令链接函数监视控制器作用域
- JavaScript - 创建可链接函数时的最佳方法是什么
- 如何将函数绑定到使用链接函数创建 HTML 的角度指令
- angularjs+ui.router:指令控制器和链接函数之间的不同行为
- 如何使用RXJS动态链接函数调用
- ES6承诺:如何用参数链接函数
- 如何创建(可选)像Lodash中那样的可链接函数
- 如何将所选元素传递给'这'在链接函数中
- 调用在Jquery中未作为链接函数工作
- 这个链接函数如何知道“;tabsCtrl"参考文献
- JS:将单参数函数转换为可链接函数
- 在指令的链接函数中修改事件中的范围变量
- 如何将服务注入链接函数包含指令
- 元素在调用链接函数时不在 DOM 中