Normal use cases in angular
If you have a parent directive and a child directive you create methods in the controller of the parent directive and require the parent controller in your child directive. Angular will pass the parent controller into your child directives link function.
My use case
I have a use case where the child directive is a parent for another directive. I have on directive on the top that is required by the directive in the middle. The middle directive is required by the last directive at the bottom.
In an easy world I could just create a link method and a controller for the middle directive. The link method handles everything with the top controller and the middle controller is passed to the bottom directive.
In my case the methods in the controller of the middle directive must call methods in the parent so I need the top-controller in the middle-controller and not in the link function of the middle directive!
The Question
How can I inject required controller into the controller instead of the link function
angular.module('app').directive('top', function () {
return {
$scope: true,
templateUrl: "top.html",
controller: function() {
this.topMethod = function() {
// do something on top
}
}
}
});
angular.module('app').directive('middle', function () {
return {
$scope: true,
templateUrl: "middle.html",
require: "^top",
controller: function($scope, $attrs, topController) {
this.middleMethod = function() {
// do something in the middle
// call something in top controller, this is the part that makes everything so complicated
topController.topMethod();
}
}
}
});
angular.module('app').directive('bottom', function () {
return {
$scope: true,
templateUrl: "bottom.html",
require: "^middle",
link: function(scope, element, attrs, middleController) {
$scope.bottomMethod = function() {
// do something at the bottom
// call something in the parent controller
middleController.middleMethod();
}
}
}
});