Register the child function of the parent when the child is initialized. I used the βhowβ for clarity in the template.
TEMPLATE
<div ng-controller="ParentCntl as p"> <div ng-controller="ChildCntl as c" ng-init="p.init(c.get)"></div> </div>
CONTROLLERS
... function ParentCntl() { var p = this; p.init = function(fnToRegister) { p.childGet = fnToRegister; };
"But," you say: " ng-init not supposed to be used that way !". Well yeah but
- that the documentation does not explain why not, and
- I do not believe that the authors of the documentation considered ALL possible use cases.
I say that is good for this. If you want to focus me, comment on the reasons! :)
I like this approach because it keeps components more modular. The only bindings are in the template and mean that
- the child controller should not know anything about which object to add its function to (as in @canttouchit's answer)
- a parent control can be used with any other child control that has a get function
- It doesnβt require a broadcast, which will be very ugly in a large application unless you strictly control the event namespace
This approach is closer to the idea of ββthermo-modulation with directives (note that in its modular example contestants passed from the parent to the "daughter" directive IN THE SAMPLE).
Indeed, another solution would be to consider implementing ChildCntl as a directive and use the & binding to register the init method.
poshest May 14 '15 at 12:27 2015-05-14 12:27
source share