角:控制器之间共享异步服务数据 [英] Angular: share asynchronous service data between controllers

查看:194
本文介绍了角:控制器之间共享异步服务数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绑定变异步数据的控制器之间。

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.

在下面的例子中,如果我在输入写东西,它的伟大工程:的http://的jsfiddle。净/ VICTA / 9NRS9 /

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();
}


但是,让我们说,我抓住从一台服务器我的数据。我想链接像在previous示例中的数据。 http://jsfiddle.net/Victa/j3KJj/

的事情是,我想尽量避免使用$广播/的$或$共享rootScope对象。

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();
}

感谢您的帮助。

维克托

推荐答案

您正在返回的工厂 的回报对象,而不是实际的对象本身。所以在你的范围,你应该真正等待的承诺修补的具体对象,然后将其分配给 $ scope.message

例如:

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

我改变了你的提琴到的东西,可能是你的回答,请参见小提琴

这篇关于角:控制器之间共享异步服务数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆