How can call a method defined in child scope from its parent scope?
function ParentCntl() {
// I want to call the $scope.get here
}
function ChildCntl($
Register the child's function on the parent when the child is initialising. I used "as" notation for clarity in the template.
TEMPLATE
CONTROLLERS
...
function ParentCntl() {
var p = this;
p.init = function(fnToRegister) {
p.childGet = fnToRegister;
};
// call p.childGet when you want
}
function ChildCntl() {
var c = this;
c.get = function() {
return "LOL";
};
}
"But", you say, "ng-init
isn't supposed to be used this way!". Well, yes, but
I say this is a good use for it. If you want to downvote me, please comment with reasons! :)
I like this approach because it keeps the components more modular. The only bindings are in the template, and means that
This approach more closely approaches Tero's idea of modularising with directives (note that in his modularised example, contestants
is passed from parent to "child" directive IN THE TEMPLATE).
Indeed another solution might be to consider implementing the ChildCntl
as a directive and use the &
binding to register the init
method.