简体   繁体   English

Angular JS:从控制器增加服务中的计数器

[英]Angular JS: Increment a Counter in a Service From Controller

I'm trying to fetch a value from an API inside my service for a counter, and then increment on that counter inside my controller:我正在尝试从我的服务内的 API 中获取一个计数器的值,然后在我的控制器内的该计数器上递增:

service服务

angular.module('app')
.factory('MyService', MyService)

function MyService($http) {
  var url = 'URL;

  return {
    fetchTotal: function(p) {
      return $http.get(url, { params: p })
        .then(function(response) {   
          var total = response.data.meta.total;
          return total;
        }, function(error) {
          console.log("error occured");
        })
    },
    incrementCounter: function(){
      total++;
    }
  }
}

controller控制器

app.controller('Controller1', function ($scope, MyService) {
    var params = {
       ...
    }

    MyService.fetchTotal(params).then(function(response) {
      $scope.counter = response;
    });

    $scope.incrementCounter = function(){
        MyService.incrementCounter();
    }
});

view看法

<div ng-controller="Controller1">
    {{ counter }}
    <span ng-click="incrementCounter()">increment</span>  
</div>

I can't work out how increment on that total I get back from the API with an ng-click .我无法计算出通过ng-click从 API 返回的总数的增量。 Is this possible?这可能吗?

Any help is appreciated.任何帮助表示赞赏。 Thanks in advance!提前致谢!

Angularjs services are singletons, so you can create variables and share it among controllers. Angularjs 服务是单例的,因此您可以创建变量并在控制器之间共享它。

Notice below how variable total is initialized in the service.请注意以下变量total在服务中是如何初始化的。 Same variable is used for interaction with the controllers by using the getCounter() method.使用getCounter()方法使用相同的变量与控制器进行交互。

Also notice the init() method.还要注意 init() 方法。 Your controller can call MyService.init first thing to initialize the total variable.您的控制器可以首先调用MyService.init来初始化total变量。

angular.module('app')
.factory('MyService', MyService)

function MyService($http) {
  var url = 'URL';
  var total = 0; /* or some other initial value*/

  return {

    init: function(){
      $http.get(url, { params: p })
        .then(function(response) {   
          total = response.data.meta.total;

        }, function(error) {
          console.log("error occured");
        });
    },
    incrementCounter: function(){
      total++;
    },
    getCounter: function(){
     return total;
    }
  }
}

See plunker for demo: http://plnkr.co/edit/idSxgm0axk43ydThTbJF?p=preview见 plunker 演示: http ://plnkr.co/edit/idSxgm0axk43ydThTbJF?p=preview

Looks like you are doing everything right, except the variable total .看起来你做的一切都正确,除了变量total

You should initialize it in an upper level so that it is also visible from incrementCounter function:您应该在较高级别对其进行初始化,以便它也可以从incrementCounter函数中看到:

function MyService($http) {
  var url = 'URL;
  var total = 0; 

  return {
    fetchTotal: function(p) {
      return $http.get(url, { params: p })
        .then(function(response) {   
          total = response.data.meta.total;
          return total;
        }, function(error) {
          console.log("error occured");
        })
     },
     incrementCounter: function(){
       total++;
     }
  }
}

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM