AngularJS : How to watch service variables?

后端 未结 21 1646
盖世英雄少女心
盖世英雄少女心 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:36

    I'm using similar approach as @dtheodot but using angular promise instead of passing callbacks

    app.service('myService', function($q) {
        var self = this,
            defer = $q.defer();
    
        this.foo = 0;
    
        this.observeFoo = function() {
            return defer.promise;
        }
    
        this.setFoo = function(foo) {
            self.foo = foo;
            defer.notify(self.foo);
        }
    })
    

    Then wherever just use myService.setFoo(foo) method to update foo on service. In your controller you can use it as:

    myService.observeFoo().then(null, null, function(foo){
        $scope.foo = foo;
    })
    

    First two arguments of then are success and error callbacks, third one is notify callback.

    Reference for $q.

提交回复
热议问题