AngularJS : How to watch service variables?

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

    You can watch the changes within the factory itself and then broadcast a change

    angular.module('MyApp').factory('aFactory', function ($rootScope) {
        // Define your factory content
        var result = {
            'key': value
        };
    
        // add a listener on a key        
        $rootScope.$watch(function () {
            return result.key;
        }, function (newValue, oldValue, scope) {
            // This is called after the key "key" has changed, a good idea is to broadcast a message that key has changed
            $rootScope.$broadcast('aFactory:keyChanged', newValue);
        }, true);
    
        return result;
    });
    

    Then in your controller:

    angular.module('MyApp').controller('aController', ['$rootScope', function ($rootScope) {
    
        $rootScope.$on('aFactory:keyChanged', function currentCityChanged(event, value) {
            // do something
        });
    }]);
    

    In this manner you put all the related factory code within its description then you can only rely on the broadcast from outside

提交回复
热议问题