Angular: Sharing Asynchronous Service Data Between Controllers

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

I know this is probably a little confusing, but I hope that something is possible.

In the following example, if I write something in the 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 the server. I would like to "bind" the data like in the previous example. http://jsfiddle.net/Victa/j3KJj/

The point is, I would like to avoid using "$ broadcast" / "$ on" or sharing an object in $ 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();
}

      

Thank you for your help.

Victor

+1


source to share


1 answer


you are returning promise

to the return object factory

, not the object itself. so in your scope you really need to wait for the promise to fix a specific object and then assign it$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

+1


source







All Articles