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

14,565

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..

  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.

Share:
14,565

Related videos on Youtube

Sajjad Ali Khan
Author by

Sajjad Ali Khan

Updated on October 22, 2022

Comments

  • Sajjad Ali Khan
    Sajjad Ali Khan over 1 year

    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.

    • Pankaj Parkar
      Pankaj Parkar over 8 years
      could you please add some code..that would clear the picture..