Angular: share asynchronous service data between c

2019-01-26 01:28发布

问题:

I would like to "bind the change" of asynchronous data between controllers.

I know it's a probably a bit confusing but I hope something is possible.

In the following example, if I write something in an input, it works great: http://jsfiddle.net/Victa/9NRS9/

HTML:

<div ng-app="myApp">
    <div ng-controller="ControllerA">
        ControllerA.message = {{message.hello}}<br/>
        <input type="text" ng-model="message.hello"/>
    </div>
    <hr/>
    <div ng-controller="ControllerB">
        ControllerB.message = {{message.hello}}<br/>
        <input type="text" ng-model="message.hello"/>       
    </div>
</div>

JS:

angular.module('myApp', [])
    .factory('myService', function($q, $timeout) {
        var message = {
            hello: 'hello world'
        };
        return {
            getMessage : function(){
                return message;
            }
       };
    })

function ControllerA($scope, myService) {
    $scope.message = myService.getMessage();
}

function ControllerB($scope, myService) {
    $scope.message = myService.getMessage();
}

But let's say I grab my data from a server. I would like to "link" the data like in the previous example. http://jsfiddle.net/Victa/j3KJj/

The thing is that I would like to avoid using "$broadcast"/"$on" or sharing the object in the $rootScope.

HTML:

<div ng-app="myApp">
    <div ng-controller="ControllerA">
        ControllerA.message = {{message.hello}}<br/>
        <input type="text" ng-model="message.hello"/>
    </div>
    <hr/>
    <div ng-controller="ControllerB">
        ControllerB.message = {{message.hello}}<br/>
        <input type="text" ng-model="message.hello"/>       
    </div>
</div>

JS:

angular.module('myApp', [])
    .factory('myService', function($q, $timeout) {
        var message = {};
        return {
            getMessage : function(){
                var deferred = $q.defer();

                $timeout(function() {
                    message.hello = 'Hello world!';
                    deferred.resolve(message);
                }, 2000);

                return deferred.promise;  
            }
       };
    })

function ControllerA($scope, myService) {
    $scope.message = myService.getMessage();
}

function ControllerB($scope, myService) {
    $scope.message = myService.getMessage();
}

Thanks for your help.

Victor

回答1:

you are returning a promise in the factory's return object and not the actual object itself. so in you scope you should actually wait for the promise to mend a concrete object then assign it to $scope.message

example:

function ControllerA($scope, myService) {
     myService.getMessage().then(function(obj){
              $scope.message=obj
             });
}

i changed your fiddle into something that might be your answer, see this fiddle