B
B
Boniface2014-03-30 13:09:07
Angular
Boniface, 2014-03-30 13:09:07

Angular.js how to pass data from one controller to another?

Hello! Friends, tell me how you transfer data from one controller to another? I know two ways to do this.
First way: Make a service that will contain common objects and read/write methods for these objects. For example:

angular.module('myModule').service('myService', function(){
    var myData = [];

    this.add = function(person){
        myData.push(person);
    };

    this.get = function(){
        return myData;
    };

    this.clear = function(){
        myData.length = 0;
    }
});

The second way is to subscribe to a specific event in the controller that needs to receive data, and raise this event in the source controller. Example:
$scope.$on('myEvent', function(event,args){
            $scope.myData.push(args);
        });

      $rootScrope.$broadcast('myEvent', myData);

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Ruslan Lopatin, 2014-03-30
@lorus

By default, objects from the parent scope are available in the child scope. So you don't even need to share data: the nested controller simply sees the data of all higher controllers.
In those rare cases when you need to exchange data with controllers outside the hierarchy, a service is written. But this service contains meaningful methods, not "put data" or "pull data" methods.
As an example: a service for displaying notifications on the screen. Contains methods for displaying notifications that interact with the controller that displays these very notifications (in the form of pop-up windows in the upper right corner of the screen, for example). Clients of this service, of course, do not know anything about the notification controller. They just don't need it.

A
Alexander Khirenko, 2014-03-30
@Satanpit

Personally, I use $rootScope.
I don't understand why there are such complications with events?

V
Vladimir Dementiev, 2016-02-02
@SayMAN83

I just started learning Angularjs and did a little test.
Having an application and several templates. I have several pages.
Created a service, a factory and a rootscope. I drove them to default values.
Further, he performed actions in which the corresponding value was transferred to all three objects (with output to div).
Then I switched to another template and returned back.
The factory and service values ​​retained their values, but the rootscope lost its value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question