You can add a custom controller to a directive by using the controller
property of the directive definition. This enables you to provide controller support for the directive template. For example, the following code adds a simple controller that sets up a scope value and function:
directive('myDirective', function() {
return {
scope: {title: '='},
controller: function ($scope){
$scope.title = "new";
$scope.myFunction = function(){
});
}
};
});
You can also use the require
option to ensure that a controller is available to the directive. The require
option uses the require:'^controller'
syntax to instruct the injector service to look in parent contexts until it finds the controller. The following is an example of requiring the myController
controller in a directive:
directive('myDirective', function() {
return {
require: '^myController'
};
});
When you add the require
option, the specified controller is passed as the fourth parameter of the link()
function. For example:
directive('myDirective', function() {
return {
require: '^myController',
link: function(scope, element, attrs, injectedMyController){
}
};
});
You can also require multiple controllers using the require
option in which case an array of controllers is passed to the link()
function. For example:
directive('myDirective', function() {
return {
require: ['^myControllerA', '^myControllerB'],
link: function(scope, element, attrs, requiredControllers){
var controllerA = requiredControllers[0];
var controller = requiredControllers[1];
}
};
});
If you specify the name of another directive in the require
option, the controller for that directive is linked. For example:
directive('myDirective', function() {
return {
require: '^myOtherDirective',
link: function(scope, element, attrs, otherDirectiveController){
}
};
});