You can pass information and functionalut in to Directives in a number fo ways. One of those ways is the controller. Most directives will have a controller associated with it which acts as a way to organize the logic you need to call upon and is a good way to add functionality to the scope. Directives can also inherit a controller from higher up in the chain which is great, however it may make it harder to use the controller you define. For an exmaple:
So how do you get a handle to the current control? Well looking through the code we can see that when we have a directive on an element it will be attached:
So to get at the current controller we just have to check the data on the current element like so:
var aControl = function() {};
var bControl = function() {};
var a = function() {
return {
link: function(scope, element, attrs, ctrl) {
// ctrl references aControl
},
controller: aControl
};
};
var b = function() {
return {
require: '^a',
link: function(scope, element, attrs, ctrl) {
// ctrl references aControl
// but how do I get a reference to bControl??
},
controller: bControl
};
};
So your control will be passed in unless you define require as can be seen in AngularJS code:
directive.require = directive.require || (directive.controller && directive.name);
So how do you get a handle to the current control? Well looking through the code we can see that when we have a directive on an element it will be attached:
$element.data('$' + directive.name + 'Controller', controllerInstance);
So to get at the current controller we just have to check the data on the current element like so:
var b = function() {
var myDirectiveName = 'b';
return {
require: '^a',
link: function(scope, element, attrs, ctrl) {
var myParentCtrl = ctrl;
var myCurrentControl = element.data('$' + myDirectiveName + 'Controller');
},
controller: bControl
};
};