I been trying to set an service object from a http post response to a controller and getting it from another controller.
The tutorials I seen in SO or sites are focused more on getting it from HTML input to a controller and another controller getting the value.
I would want to avoid using rootscope and I'm new to angular-js.
First Controller(To Put Data1 & Data2 in an object)
.controller('GetItem',function($scope, $http, $filter, $ionicPopup, $stateParams, $cordovaSQLite, $cordovaDatePicker, dataFactory){
...
console.log(resp.data);
var data1= resp.data.data1;
var data2= resp.data.data2;
}
2nd Controller (To get the object and retrieve data1 and data2)
Some pointers would be deeply appreciated!
Update1: (Save Function Works but Get Function Returns EMPTY):
.service('StoreService',function(){
var data1=[]; //{} returns me an empty object
this.save=function(data1){
alert('DATA: '+ data1); //able to retrieve string
this.data1=data1;
};
this.getData1=function(){
alert('DATA1: '+ data1); //unable to get string
return data1;
};
})
This is the 2nd Controller which retrieve from service:
.controller('unlock', function($scope, $timeout, dataFactory, $stateParams,StoreService) {
function test(){
console.log(StoreService.getData1());
Update 2: (Working) Tomislav's plunker : http://plnkr.co/edit/srAphQhAYuBZL18MY1Kr?p=preview
@atinder answer is way to go. Here is the example of the service:
app.service('StoreService',function(){
var data1={};
var data2={};
this.save=function(data1,data2){
this.data1=data1;
this.data2=data2;
};
this.getData1=function(){
return data1;
};
this.getData2=function(){
return data2;
};
});
Then in first controller:
.controller('firstController',function(StoreService){
.....
StoreService.save(resp.data.data1,resp.data.data2);
});
In second controller:
.controller('secondController',function(StoreService,$scope){
$scope.data1 = StoreService.getData1();
$scope.data2 = StoreService.getData2();
});
create a basic service with setters and getters. Inject the service into both the controllers. use setter in one controller and getter in the another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With