AngularJS : How to watch service variables?

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

    Here's my generic approach.

    mainApp.service('aService',[function(){
            var self = this;
            var callbacks = {};
    
            this.foo = '';
    
            this.watch = function(variable, callback) {
                if (typeof(self[variable]) !== 'undefined') {
                    if (!callbacks[variable]) {
                        callbacks[variable] = [];
                    }
                    callbacks[variable].push(callback);
                }
            }
    
            this.notifyWatchersOn = function(variable) {
                if (!self[variable]) return;
                if (!callbacks[variable]) return;
    
                angular.forEach(callbacks[variable], function(callback, key){
                    callback(self[variable]);
                });
            }
    
            this.changeFoo = function(newValue) {
                self.foo = newValue;
                self.notifyWatchersOn('foo');
            }
    
        }]);
    

    In Your Controller

    function FooCtrl($scope, aService) {
        $scope.foo;
    
        $scope._initWatchers = function() {
            aService.watch('foo', $scope._onFooChange);
        }
    
        $scope._onFooChange = function(newValue) {
            $scope.foo = newValue;
        }
    
        $scope._initWatchers();
    
    }
    
    FooCtrl.$inject = ['$scope', 'aService'];
    

提交回复
热议问题