This plunkr throws this error:
Error: [$compile:ctreq] Controller 'childDirective', required by directive 'parentDirective', can't be found!
I can work around this, but I'm curious if this is by-design, and why (single parent vs multiple children thing)? I don't see any mention of this restriction in the $ng.compile docs.
The reason this isn't implemented is performance. Traversing up the DOM is alot faster than checking each child branch for a possible match. For this reason the recommended way is to let child element inform their parent of their status.
Note that this is done via the associated controller instances, not via the directives.
I've updated your plunk with a working example
angular.module('foo', [])
.directive('parentDirective', function() {
return {
controller: function($scope) {
$scope.childs = {};
this.registerChild = function(child) {
$scope.childs[child.name] = child;
};
},
link: function(scope, element, attrs) {}
};
})
.directive('childDirective', function() {
return {
controller: function($scope) {},
require: ['^parentDirective', 'childDirective'],
link: function($scope, $element, $attrs, $ctrls) {
var parent = $ctrls[0];
var child = $ctrls[1];
child.name = $attrs.childDirective;
parent.registerChild(child);
}
};
});
You can't require a child directive, as far as I know nothing in Angular allows this. You can only require a parent directive from a child, by
require: '^parentDirectiveName'
or a sibling directive, by
require: 'siblingDirectiveName'
So yes, this is by design, or at least a lack of feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With