Currently, I am working on developing a factory for the restful services.
The main challenge I'm facing is how to transfer data from one controller to another in AngularJS. Specifically, I need to use the data obtained from the first service call to make a subsequent service call and retrieve additional data.
I wonder if there's a more efficient way to structure my code to handle this scenario...
Below are the snippets of code I have so far:
var app = angular.module('myApp', []);
// Retrieving initial data through a service
app.factory('myService', function($http) {
var myService = {
async: function() {
var promise = $http.get('test/test.json').then(function (response) {
return response.data;
});
return promise;
}
};
return myService;
});
// Controller for handling data retrieval
app.controller('testCtrl', function(myService, $scope, $http) {
myService.async().then(function(data) {
$scope.data = data
// Using retrieved data to fetch additional information
vay first = data[0].employee[0];
})
$http({
url: "test?" + first +'.json',
method: "GET",
}).success(function(secondData) {
$scope.secondData=secondData // How can I pass this data to secondCtrl?
})
})
app.controller('secondCtrl', function($scope) {
// I need access to the 'secondData' from testCtrl.
console.log($scope.secondData)
})
Your insights and suggestions would be greatly appreciated. Thank you!