提供角色服务以维持柜台

时间:2016-01-07 16:59:36

标签: angularjs state angular-services

我正在尝试使用角度服务。作为测试,我想制作一个简单的计数器,它在多个控制器和整个浏览器生命周期中递增。我的服务似乎在每个控制器中重新初始化,任何想法?

注意:控制器位于不同的页面上 - 因此页面重新加载

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;
    };

});

然后在控制器中我打电话

Session.inc();

Session.get();

1 个答案:

答案 0 :(得分:1)

您的设置没问题,但您的逻辑错误:

   this.inc = function() {
        console.log("INC Called and Global is :" + this.count);
        if(this.count) {
            this.count++;
        } else {
            this.count = 0;
        }

   };

第一次运行时,this.count将初始化为0,每次下次评估为false。将其更改为:

 this.count = 0;
 this.inc = function() {
    this.count++;
 };

更容易理解。

Plnkr:http://plnkr.co/edit/WoPVQZuzQ7Ow781OOgtj?p=preview

编辑:似乎作者正在尝试维护服务状态而不是页面更改。为此,您可以使用localstorage:

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