Reputation: 149
I have written a service described below
myApp.service('dashboardPath', function(){
var path;
return {
path: path
}
this.path = function(value){
path = value;
}
});
am setting the value of path in sessionsCtrl like this dashboardPath.path = "student_dashboard" and i can access the value of path in any controller like dashboardPath.path which is returning the correct value, but if i reload the page the value of path is gone(it says "undefined"). Is my above service defined properly?
Upvotes: 1
Views: 111
Reputation: 12343
this code looks strange:
myApp.service('dashboardPath', function(){
var path;
return {
path: path
}
this.path = function(value){
path = value;
}
});
return
sentences are not needed since such function is called using new
operator. yoor code should be:
myApp.service('dashboardPath', function(){
var path;
this.path = path;
});
you need to -actually- store the value. By having it in just a variable, the context will be reset when you refresh, and you will still get the undefined
you say. You should store it in one of three places:
get
and post
the value.in any of such places you'll need to have a setter and getter for such values:
this.getPath = function(){ ... };
this.setPath = function(v){ ... };
instead of the plain member variable path
.
Upvotes: 0
Reputation: 11752
When you refresh the page the value will disappear because the app reloads. What you need is persistence of data:
myApp.service('dashboardPath', function(){
var path = JSON.parse(localStorage.getItem('path'));
this.path = function(value){
path = value;
localStorage.setItem("path", path);
};
return {
path: path
}
});
Upvotes: 2
Reputation: 4202
Services are singleton objects that will live for the duration of your application. Refreshing the page reloads all the code and ditches the old memory. Your code is working correctly.
If you want to persist data between page refreshes, try using localStorage.
Upvotes: 0