gfaceless
gfaceless

Reputation: 1559

AngularJS - dynamically created directive's "require" not working

The "require" option does not work if the directive is dynamically created, thus it cannot reference its parents' controllers. How can I make it work?

app.directive('parent', function ($compile) {
  return {
    controller: function() {},
    link: function (scope, el, attrs) {
      // "child" is dynamically created
      el.append( $compile('<div child>')(scope) );
    }
  }
})

.directive('child', function () {
  return {
    require: "?^parent",
    link: function(scope, el, attrs, pCtrl) {
      // "child" cannot find its parent controller
      console.log("pCtrl is undefined: ", pCtrl);
    }
  }
})

here is a plunker DEMO

Upvotes: 3

Views: 1755

Answers (1)

dhavalcengg
dhavalcengg

Reputation: 4713

you need to add child element to parent element before compiling it.

When directive compiles, its tries to get its parent element. And from parent element it tries to find parent controller. But you are compiling your child directive before appending its element to its parent element.

I have created a plnkr for you. Checkout this

app.directive('parent1', function($compile, $timeout) {
  return {
    controller: function() {
      this.name = 'parent controller 1';
    },
    link: function(scope, el, attrs) {
      // "child1" is dynamically created
     var elmChild = angular.element('<div child1>');
      el.append(elmChild);
      $compile(elmChild)(scope);
    }
  }
})

Upvotes: 9

Related Questions