How do I access the child and parent controller in a directive?
We have two directives called parent
and child
. Both of them have specific controllers that have some functionality. For a directive, child
we can:
- access
parent controller
with therequire
(require: '^parent'
) property , thus getting the fourth parameter of our communication function with its value:function link(scope, elem, attrs, parentCtrl)
- access
child controller
: without usingrequire
the fourth link parameter will be our childController.
So the question is, how can we link to both child and parent controllers in the child
link function ? Here's a plunker with an example: http://plnkr.co/edit/WzU6iJgf2zLLApFHeiEG?p=preview
+3
source to share
1 answer
You can pass an array to the require property to define your directive, which includes both your child directive and your parent directive. The fourth parameter for your link function will be an array:
app.directive('childDirective', function() {
require: ['childDirective', '^parentDirective'],
link: function(scope, element, attr, ctrls) {
var childCtrl = ctrls[0];
var parentCtrl = ctrls[1];
...
}
});
+5
source to share