Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 992
gfaceless Avatar asked May 01 '26 08:05

gfaceless


1 Answers

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);
    }
  }
})
like image 200
dhavalcengg Avatar answered May 04 '26 03:05

dhavalcengg