Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data from child controller to Parent controller in AngularJS?

I need some guidance to take the best practice for my task in AngularJS.

Task:

  1. Inside the view : I have one parent controller and two child controllers.
  2. Child controllers work with their own $scope and objects.
  3. 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.

like image 891
Sajjad Ali Khan Avatar asked Oct 18 '15 19:10

Sajjad Ali Khan


2 Answers

A common way of sharing data between controllers is to use use a service.

You could also broadcast updates to the parent controller

like image 57
user2954587 Avatar answered Oct 04 '22 04:10

user2954587


There are many different ways to achieve this..

  1. Using $rootScope.
  2. Using Services
  3. Use broadcast and emit
  4. 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.

like image 25
Ritt Avatar answered Oct 04 '22 03:10

Ritt