thatmarvin
thatmarvin

Reputation: 2880

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.

Upvotes: 3

Views: 1268

Answers (2)

null
null

Reputation: 7926

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);
    }
  };
});

Upvotes: 6

Michal Charemza
Michal Charemza

Reputation: 27012

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.

Upvotes: 1

Related Questions