Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I require a child directive from a parent directive?

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.

like image 444
thatmarvin Avatar asked Nov 29 '25 10:11

thatmarvin


2 Answers

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);
    }
  };
});
like image 136
null Avatar answered Dec 01 '25 01:12

null


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.

like image 25
Michal Charemza Avatar answered Dec 01 '25 00:12

Michal Charemza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!