How to send data from a child controller to a parent controller in AngularJS?

I need to be guided by best practice for my task in AngularJS.

Task:

  • Inside the view: I have one parent controller and two child controllers.
  • Real controllers work with their own $ domain and objects.
  • When I click the "Save" button in the view, I need to get data from the child controllers to the parent controller in order to prepare the object for sending it to the server.

I am confused about what is the best solution for this approach.

+7
json javascript angularjs
source share
3 answers

A common way to share data between controllers is to use service .

You can also broadcast update the parent controller

+5
source share

There are many different ways to achieve this.

  • Using $ rootScope.
  • Using Services
  • Use broadcast and emit
  • Declare an object in the parent controller, and then modify the same object in the child controller.

Using $ rootScope is not a good approach, since the $ rootScope variable is destroyed when the application is closed.

I will also not recommend broadCast or emit until it is needed.

Services are good for b / w communication controllers, but again you enter them and change the methods.

In your scenario, I would recommend using a common $ scope object variable, which is declared inside the parent and used in child controllers, since all methods are inherited in child controllers.

+1
source share

There are three general ways to exchange data between controllers:

1 put the data in the service or factory. Since they are single point, any controller injected with the same service can share data in this service

2 put the data in $rootScope

3 use $broadcast or $emit to send events between areas and pass shared data as event arguments

0
source share

All Articles