Reputation: 584
Hi i have two controllers and in one i have defined some function to get me a data,i stored the data in $scope.data1, now i want to access this $scope.data1 data in some another named controller so that i may access the same on other page when loaded via route.How may i do so.
here is what my code is.
commonApp.service('CommonServices',function($http){
this.getData=function(urlreq){
return $http({
method:"GET",
url :urlreq
});
};
commonApp.controller('Controller1',function($scope,CommonServices,toaster){
CommonServices.getData('dataurl1').success(function(getResponse){
$scope.data1=getResponse.success;
};
}
commonApp.controller('Controller2',function($scope,CommonServices,toaster){
$scope.data2= ????;
//i want my $scope.data1 in $scop.data2.
}
});
Upvotes: 3
Views: 429
Reputation: 21662
I believe you are looking for something like this, where you use the same common service to store a piece of data that can be fetched by any controller that has access to the service:
commonApp.service('CommonServices', function ($http) {
this.shared = null; // this is where the shared data would go
this.getData = function (urlreq) {
return $http({
method: "GET",
url: urlreq
});
};
this.setSharedData = function (data) { // this sets the value of the shared data
this.shared = data;
};
this.getSharedData = function () { // this retrieves the shared data
return this.shared;
}
});
commonApp.controller('Controller1', function ($scope, CommonServices, toaster) {
CommonServices.getData('dataurl1').success(function (getResponse) {
$scope.data1 = getResponse.success;
CommonServices.setSharedData($scope.data1);
// CommonServices.shared = $scope.data1; // this would also work
});
});
commonApp.controller('Controller2', function ($scope, CommonServices, toaster) {
$scope.data2 = CommonServices.getSharedData();
// $scope.data2 = CommonServices.shared; // this would also work
});
I based this upon your own sample code, though I would probably structure things differently. But it makes the basic point, and I assume your actual need is a bit more complex.
Note that you don't need to use setters and getters in the service, though it might make sense depending on the need for adding things like null checking and overwriting existing values. You'll see in the comments that I've included an example of how you could manipulate the service's properties directly without the setting and getting functions.
Hope this helps, and don't forget to upvote and select an accepted answer.
Upvotes: 3
Reputation: 140
You could save the shared data in the service. For example if you define the service as a factory:
commonApp.factory('commonFactory', ['$http', function ($http) {
return {
commonData: null
};
}]);
After in the controllers you can access this commonData to store and get data from it.
First controller:
commonFactory.commonData = getResponse.success;
Second controller:
$scope.data2= commonFactory.commonData;
Upvotes: 1