Update scope value when service data is changed

后端 未结 6 1254
天命终不由人
天命终不由人 2020-11-27 10:57

I have the following service in my app:

uaInProgressApp.factory(\'uaProgressService\', 
    function(uaApiInterface, $timeout, $rootScope){
        var facto         


        
6条回答
  •  一个人的身影
    2020-11-27 11:33

    Lightweight alternative is that during controller initialization you subscribe to a notifier pattern set up in the service.

    Something like:

    app.controller('YourCtrl'['yourSvc', function(yourSvc){
        yourSvc.awaitUpdate('YourCtrl',function(){
            $scope.someValue = yourSvc.someValue;
        });
    }]);
    

    And the service has something like:

    app.service('yourSvc', ['$http',function($http){
        var self = this;
        self.notificationSubscribers={};
        self.awaitUpdate=function(key,callback){
            self.notificationSubscribers[key]=callback;
        };
        self.notifySubscribers=function(){
            angular.forEach(self.notificationSubscribers,
                function(callback,key){
                    callback();
                });
        };
        $http.get('someUrl').then(
            function(response){
                self.importantData=response.data;
                self.notifySubscribers();
            }
        );
    }]);
    

    This can let you fine tune more carefully when your controllers refresh from a service.

提交回复
热议问题