Angular Directive, accessing the controller
1) Accessing required dependent directive controllers:
.directive('myDirRequiresNgModel', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElement, iAttributes, ctrl){
//ctrl is the ngModel controller
}
};
}]);
2) Accessing multiple required directive controllers
.directive('myDirRequiresNgModel', function(){
return {
restrict: 'A',
require: ['ngModel','form'],
link: function(scope, iElement, iAttributes, ctrl){
//ctrl is the array of controllers [ngModel, ngForm]
}
};
}]);
3) Accessing parent required controller (living upwards in the dom tree
.directive('myDirRequiresNgModel', function(){
return {
restrict: 'A',
require: '^form', // a '?^form' makes it optional
link: function(scope, iElement, iAttributes, ctrl){
//ctrl is the ngForm controller from the nearest parent with the directive
}
};
}]);
4) Accessing this controller the simple way
.directive('myDirRequiresNgModel', function(){
return {
restrict: 'A',
controller: 'MyController',
link: function(scope, iElement, iAttributes, ctrl){
//ctrl is the MyController object
}
};
}]);
5) Accessing both MyController and ngModel (or any other directive controller)
.directive('myDirRequiresNgModel', function(){
return {
restrict: 'A',
require: ['ngModel', 'myCtrl'],
controller: 'MyController'
link: function(scope, iElement, iAttributes, ctrl){
//ctrl is [ngModel, MyController]
}
};
}]).controller('MyController', function(){
this.id = 'myCtrl'; // this is how it looks up the ctrl, apparently!
});
Written by Alex Lockwood
Related protips
1 Response
I was looking into my options for using the functionality you explain here but your last example (#5) did not work for me.
I was able to get my directives to work with both a require on the parent directive and the current child directive. Here is an explanation on a stackoverflow question I answered ( http://stackoverflow.com/questions/21342698/controller-required-by-directive-cant-be-found/ ) and here is my functioning example on github ( https://github.com/sgwatgit/angular-directives-communication )