How to send data from child controller to Parent controller in AngularJS?
Solution 1
A common way of sharing data between controllers is to use use a service.
You could also broadcast updates to the parent controller
Solution 2
There are many different ways to achieve this..
- Using $rootScope.
- Using Services
- Use broadcast and emit
- Declare an object in parent controller and then modify the same object in the child controller.
Using $rootScope is not a good approach, as the $rootScope variable is destroyed when application is closed.
I will also not recommend broadCast or emit, until it's required.
Services, is good for communication b/w controllers, but again you have inject it and modify the methods.
In your, scenario, i would recommend to use the common $scope object variable, which is declared inside parent and used in child controllers, as all methods are inherited in the child controllers.
Related videos on Youtube
Sajjad Ali Khan
Updated on October 22, 2022Comments
-
Sajjad Ali Khan over 1 year
I need some guidance to take the best practice for my task in AngularJS.
Task:
- Inside the view : I have one parent controller and two child controllers.
- Child controllers work with their own $scope and objects.
- When I press save in the view, I need to get the data from child controllers to parent controller in order to prepare an object for posting it to the server.
I am getting confused of what is the best solution for this approach.
-
Pankaj Parkar over 8 yearscould you please add some code..that would clear the picture..