简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM