如何在角度即服务中创建全局计数器

时间:2014-03-31 12:25:33

标签: angularjs

我是AngularJS的新手,我想知道,如何通过“服务”更改全球价值?

我构建了一个简单的app-services,其中包括“count” - 变量和“增加”函数。

myApp.service("itemCount", function(){
  var count = 1;
  this.count = count;
  return {
    count: this.count,
    increase: function(){
      this.count = this.count + 1;
      return this.count;
    }
  // maxItems: --> TodoCtrl $scopes.todos.length 
  }
});

我建立了一个简单的待办事项清单:

myApp.controller('TodoCtrl', function($scope, $http, itemCount) {
  $http.get('todos.json')
       .success(function(data){
          $scope.todos = data;       
          var start = 0;
          $scope.todo = $scope.todos[start];
          $scope.nextTodo = function(num){
            if(num < $scope.todos.length){
              $scope.todo = $scope.todos[num];
              itemCount.increase();
              console.log("count = " + itemCount.count);
            }
          };
        });
});

至少我建立了一个“进步” - 控制:

myApp.controller('ProgressCtrl', function ($scope, itemCount) {

    $scope.max = 10; // hard coded
    $scope.value = itemCount.count;

});

我如何实现,我的“进度”控制获得最新的计数值?

示例:http://plnkr.co/edit/dCinO4iGDfql40GStGr2

寻求帮助

1 个答案:

答案 0 :(得分:2)

使用函数而不是变量获取值,或者将服务添加到范围。

http://plnkr.co/edit/LBISC3RhIAKgtgXJjUDD?p=preview

{{getCount()}} / {{max}}
{{itemService.count}} / {{max}}


myApp.controller('ProgressCtrl', function ($scope, itemCount) {
    $scope.max = 10; // hard coded
    $scope.value = itemCount.count;
    $scope.getCount = function(){ return itemCount.count; };
    $scope.itemService = itemCount;
});