0

In my angular application, I want to invoke a function from a nested controller. For example, below I want in this current view of container, which has its own containerCtrl lets say, to be able to press this button but invoke a function called 'buttonPress' that is defined in the Ctrl1 controller. Right now, I can't do that since, well its just not defined within the containerCtrl scope.

HTML:

<div id="container">
    <button ng-click="Ctrl1.buttonPress()">I WANT TO PRESS THIS</button>
    <div ng-controller='Ctrl1'>
    <div ng-controller='Ctrl2'>
</div>

Is there some way to invoke that function?

puopg
  • 563
  • 7
  • 17
  • Your nesting doesn't make sense. Your button isn't in scope of Ctrl1. Create a demo with what you are trying to do – charlietfl Apr 09 '15 at 19:33
  • Yea like, thats exactly my point. As i stated, i'm well aware that I cannot invoke buttonPress from this current scope. Im asking, is it possible though? – puopg Apr 09 '15 at 21:35
  • Not with what's shown so far... why are you needing to call method that's not in scope? – charlietfl Apr 09 '15 at 21:37
  • The real scenario would be lets say I have 2 controllers each which have some data I want to save to the database. I would like to make 1 request to the server so instead of sending one part at a time, what if my parent could get that data from both controllers and then issue a single request? Potentially, is this the idea of using shared models? – puopg Apr 09 '15 at 21:45
  • Sure, you can share data across many controllers by using a service. Can also share functions – charlietfl Apr 09 '15 at 21:48
  • Awesome, yea this is what I had to do. Going to take a while, but i think a refactor is necessary. Thanks! – puopg Apr 10 '15 at 00:26

1 Answers1

-1

So you want to call buttonPress() method which is in child controller from parent controller,in your case it is from containerCtrl to Ctrl1. You can only call the methods of parent controller from child controller.

Why you want to to call it from parent controller.Why not directly define it Parent and then call it from parent or from any child controllers.

One way of doing it is you can use emit and broadcast.

Check out this link to know more about emit and broadcast

Working with $scope.$emit and $scope.$on

Community
  • 1
  • 1
Ritt
  • 3,181
  • 3
  • 22
  • 51
  • Is this a bad practice to use to get parent controllers talking with children? Is it bad in general for the parent to even be talking to the child? – puopg Apr 09 '15 at 21:37
  • Scope in angular js uses inheritance.when looking up a property in child scope,the chain starts from the child and continues to the parent,until the property is found.Use services to share data between controllers or use $emit or $broadcast. – Ritt Apr 10 '15 at 03:29