angularjs - Making an Angular Service to Maintain a counter -
i trying experiment angular services. test wanted make simple counter incremented across multiple controllers , throughout browser life cycle. service seems re-initialized in each controller, ideas ?
note: controllers on different pages - there page reload
angular.module('myapp').service('session', function($http) { this.inc = function() { console.log("inc called , global :" + this.count); if(this.count) { this.count++; } else { this.count = 0; } }; this.get = function() { return this.count; }; });
and in controller call
session.inc();
and
session.get();
your setup ok, logic wrong:
this.inc = function() { console.log("inc called , global :" + this.count); if(this.count) { this.count++; } else { this.count = 0; } };
first time it's ran, this.count
initialized 0
evaluate false every next time. change to:
this.count = 0; this.inc = function() { this.count++; };
much more understandable.
plnkr: http://plnkr.co/edit/wopvqzuzq7ow781oogtj?p=preview
edit: seems author trying maintain service state on page changes. in order that, can use localstorage:
this.count = localstorage.getitem('counter') || 0; this.inc = function() { this.count++; localstorage.setitem('counter', this.count); };
Comments
Post a Comment