I'm currently exploring how to establish communication between two directives through their respective controllers in Angular. As a newcomer to the framework, I still have some uncertainties that need clarification.
My objective is simple: I want two distinct directives where, upon clicking on an element within directive A, a specific function within B gets triggered. Essentially, I aim to instruct B to update itself based on the actions that occur within A. Here's what I've managed to put together so far:
app.directive('A', function(){
return{
restrict: 'E',
require:'B',
templateUrl:'a.html',
link: function(scope, element, attr, bController){
//Should I execute B's behavior here?
//How can I access B's controller from here?
},
controller: function(){
//Or maybe here?
//How do I reach B's controller in this context?
},
controllerAs:'A'
};
});
app.directive('B', function(){
return{
restrict: 'E',
templateUrl:'b.html',
link: function(scope, element, attr){
},
controller: function(){
//This section will contain functions to handle
//manipulation of elements within this directive (B)
},
controllerAs:'B'
};
});
An error occurs as A attempts to locate the controller named B, but it is a directive: https://docs.angularjs.org/error/$compile/ctreq
Furthermore, should DOM manipulation be carried out within the link
function or the directive's controller? Despite my readings, I still find the distinction between link
and controller
a bit cloudy; from my understanding, link
is akin to a constructor while the controller houses the actual functionality.
Does this imply that all DOM manipulations belong inside the controller?
Are there alternative approaches to address this issue? I have come across information about $scope
, yet its concept remains somewhat elusive to me.