avrono
avrono

Reputation: 1680

Making an Angular Service to Maintain a counter

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

Answers (1)

Igor Pantović
Igor Pantović

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

Edit: It seems that author is trying to maintain service state over page changes. In order to do that, you can use localstorage:

 this.count = localStorage.getItem('counter') || 0;
 this.inc = function() {
    this.count++;
    localStorage.setItem('counter', this.count);
 };

Upvotes: 1

Related Questions