If we want to expose an API to other directives, we should
require a controller on the directive.
We can bind a controller to the directive with
require. Multiple controllers can be required by using an array of strings.
app.directive('foo', function() {
return {
require: 'bar',
}
});
Link function
When a controller is required, it will be passed as the 4th argument to the link function:
app.directive('foo', function() {
return {
require: 'bar',
link: function (scope, element, attrs, bar) {
}
}
});
When multiple controllers are required, they will be passed as an array to the link function:
app.directive('foo', function() {
return {
require: ['bar, baz'],
link: function (scope, element, attrs, controllers) {
var bar = controllers[0];
var baz = controllers[1];
}
}
});
Controller location
We can control where the controller can be found by prefixing the controller name as follows:
no prefix
The required controller must be specified on the directive itself. An exception is thrown if no controller is found.
?
Make the controller optional - if it is not found in the directive provided, null is passed as the 4th argument to
the link function.
ˆ
Walk up the parent chain until the controller is found
?ˆ
Combine the previous two options - walk up the parent chain until the controller is found, and pass null if none is found