AngularJS : How to watch service variables?

后端 未结 21 1653
盖世英雄少女心
盖世英雄少女心 2020-11-22 09:12

I have a service, say:

factory(\'aService\', [\'$rootScope\', \'$resource\', function ($rootScope, $resource) {
  var service = {
    foo: []
  };

  return          


        
21条回答
  •  不要未来只要你来
    2020-11-22 09:41

    Without watches or observer callbacks (http://jsfiddle.net/zymotik/853wvv7s/):

    JavaScript:

    angular.module("Demo", [])
        .factory("DemoService", function($timeout) {
    
            function DemoService() {
                var self = this;
                self.name = "Demo Service";
    
                self.count = 0;
    
                self.counter = function(){
                    self.count++;
                    $timeout(self.counter, 1000);
                }
    
                self.addOneHundred = function(){
                    self.count+=100;
                }
    
                self.counter();
            }
    
            return new DemoService();
    
        })
        .controller("DemoController", function($scope, DemoService) {
    
            $scope.service = DemoService;
    
            $scope.minusOneHundred = function() {
                DemoService.count -= 100;
            }
    
        });
    

    HTML

    {{service.name}}

    Count: {{service.count}}

    This JavaScript works as we are passing an object back from the service rather than a value. When a JavaScript object is returned from a service, Angular adds watches to all of its properties.

    Also note that I am using 'var self = this' as I need to keep a reference to the original object when the $timeout executes, otherwise 'this' will refer to the window object.

提交回复
热议问题