dev777 dev777 - 4 months ago 14
AngularJS Question

How to send data from one controller to other in angularjs

How to send the json data from FirstCtrl to secondCtrl using angularjs.

Can anyone please help me out regarding this ...

First.js:

angular.module('myApp')
.controller('FirstCtrl', function ($scope) {

//firstCtrl json data
$.getJSON("sample.json", function (json) {
console.log(json);
});
});


Second.js:

angular.module('myApp')
.controller('secondCtrl', function ($scope) {

//get the firstCtrl json data here
});

Answer

I would also suggest a service that gets and returns data from and to the controllers.

we create the two controllers and then we create a service with two functions: 1. one to get the json data 2. one to return the json data

Like so:

'use strict';
angular.module('myApp', [])

.controller('FirstCtrl', function( $scope, myService ){
 //we create or get the json object
 $scope.myjsonObj = {
      'animal':'cat',
      'feed':'frieskies',
      'color':'white',
      'sex':'male'
      };

      //pass the json object to the service
      myService.setJson($scope.myjsonObj);
})

.controller('SecondCtrl', function( $scope, myService ){
        //call service getJson() function to get the data
       $scope.myreturnedData = myService.getJson();
})
 .factory('myService', function(){
    var myjsonObj = null;//the object to hold our data
     return {
     getJson:function(){
       return myjsonObj;
     },
     setJson:function(value){
      myjsonObj = value;
     }
     }

});

and the HTML partial would be:

 <div ng-app="myApp">
        <div ng-controller="FirstCtrl">
          {{myjsonObj}}
        </div>
        <hr>
        <div ng-controller="SecondCtrl">
            {{myreturnedData.animal}}
            {{myreturnedData.feed}}
            {{myreturnedData.color}}
            {{myreturnedData.sex}}
        </div>

Hope helps, good luck.