hba
hba

Reputation: 7790

Angular JS directive specific controller & parent controller

I would like to use a directive specific controller and the parent controller in the link function.

module.directive('parent', function() {
    return {
              ...
              controller: SomeFunction
           }
}

module.directive('child', function() {
        return {
              ...
              require('^parent'),
              controller: SomeOtherFunction,
              link: function(scope, element, attr, ctrl) {
                 //ctrl is the parent controller not the SomeOtherFunction
              }
           }
}

Is there a way I can use directiveSpecificController but also have access to the parent controller?

Upvotes: 1

Views: 76

Answers (1)

Peter Ashwell
Peter Ashwell

Reputation: 4302

Yes, you just need to require your own controller too:

http://plnkr.co/edit/2x7yxRfJWqXi1FfZmb3V?p=preview

app.directive('parent', function() {
  return {
    controller: function() {
      this.secret = 'apples';
    }
  }
})

app.directive('child', function() {
  return {
    controller: function() {
      this.secret = 'oranges';
    },
    require: ['child', '^parent'],
    link: function(scope, elem, attrs, ctrls) {
      var parentCtrl = ctrls[1];
      var childCtrl = ctrls[0]
      console.log(parentCtrl.secret);
      console.log(childCtrl.secret);
    }
  }
})

Upvotes: 2

Related Questions