Reputation: 1680
I am trying to experiment with angular services. As a test I wanted to make a simple counter which incremented across multiple controllers and throughout the browser life cycle. My service seems to be re-initialized in each controller, any ideas ?
NOTE: Controllers are on different pages - so there is a page reload
angular.module('myApp').service('Session', function($http) {
this.inc = function() {
console.log("INC Called and Global is :" + this.count);
if(this.count) {
this.count++;
} else {
this.count = 0;
}
};
this.get = function() {
return this.count;
};
});
And then in the controller I call
Session.inc();
and
Session.get();
Upvotes: 0
Views: 1563
Reputation: 9246
Your setup is ok, but your logic is wrong:
this.inc = function() {
console.log("INC Called and Global is :" + this.count);
if(this.count) {
this.count++;
} else {
this.count = 0;
}
};
First time it's ran, this.count
will be initialized to 0
which will evaluate to false every next time. Change it to:
this.count = 0;
this.inc = function() {
this.count++;
};
Much more understandable.
Plnkr: http://plnkr.co/edit/WoPVQZuzQ7Ow781OOgtj?p=preview
this.count = localStorage.getItem('counter') || 0;
this.inc = function() {
this.count++;
localStorage.setItem('counter', this.count);
};
Upvotes: 1