0

I need a directive ngTree to get the controller of a parent ngTree element. Note that require: "^ngTree" would return the controller of current directive.

I know I could do a ngTreeHelper and put a div with it, between any two ngTree divs and require: "^ngTreeHelper" would work, but it's ugly. I wonder if there is something else I could do.

Karolis Juodelė
  • 3,708
  • 1
  • 19
  • 32
  • "Note that require: "^ngTree" would return the controller of current directive." - are you sure about that? – Stewie Nov 30 '13 at 08:06
  • Yes, besides actually trying it, I've seen it explained in another SO answer ["^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive"](http://stackoverflow.com/a/15691865/971193). The "in addition" is a problem. – Karolis Juodelė Nov 30 '13 at 09:03

1 Answers1

0

There's not a great built in way to do this. However it is done in angular's form directive.

Swiping the code from there, this is what you need

var ngTreeController = $element.parent().controller('ngTree');

This is in the form directive's controller, but you should be able to do this from a link function too.

Andyrooger
  • 6,748
  • 1
  • 43
  • 44
  • Thanks. To add to the answer, [controller(name) - retrieves the controller of the current element or its parent. By default retrieves controller associated with the ngController directive. If name is provided as camelCase directive name, then the controller for this directive will be retrieved (e.g. 'ngModel').](http://docs.angularjs.org/api/angular.element) – Karolis Juodelė Nov 30 '13 at 17:51
  • Yep, and `.parent()` skips the current element, and so avoids taking the controller from the current `ngTree` as it would using `require`. – Andyrooger Nov 30 '13 at 18:02