AngularJs: Sharing Data Across Controllers
Solution 1:
There is a solution but it needs some additional configuration while making routes in your $routeProvider
, You can resolve your route when you have your data fetch from the backend. By using this method if a user refreshes the page on one of your project it will receive the data first then display that particular page.
First you have to modify your dataFactory
something like this
app.service('MyService', function($http) {
var myData = null;
var promise = promise || $http.get('data.json').success(function (data) {
myData = data;
});
return {
promise:promise,
doStuff: function () {
return myData
}
};
});
Then in your $routeProvider
you could make route to resolve when your data is fetched (that is receives its promise) more over by using this method it wont make another data call if your data is stored.
app.config(function($routeProvider){
$routeProvider
.when('/',{controller:'MainCtrl',
template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
resolve:{
'MyServiceData':function(MyService){
return MyService.promise;
}
}})
.when('/b',{controller:'MainCtrl2',
template:'<div>From MyServic2e:<pre>{{data | json}}</pre></div>',
resolve:{
'MyServiceData':function(MyService){
return MyService.promise;
}
}})
})
I've a made a working Plunker for demo. Fell free to ask any question regarding this.
Hope it helps.
Solution 2:
when you refersh the page, the app module loads again wiping out all the stored vars. You can use sessionStorage or localStorage to maintain data.
Solution 3:
When you store your data into service/ factory
store it in to your browser's local storage
too. So, when user refresh the page, you can check whether your local storage
has the data or not. If there is data in your local storage
just save these data into your service/ factory
.
That's all !!!
If you are struggle to implement these things please update me, I can help you on the code also.
Post a Comment for "AngularJs: Sharing Data Across Controllers"