角:控制器之间的更新服务,并共享数据 [英] Angular: Update service and share data between controllers

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

问题描述

我使用的是服务,抓住从一个API的一些数据:

I'm using a service to grab some data from an API:

angular.module('myApp', [])
.factory('myService', function($q, $timeout) {
    var getMessages = function() {
        var deferred = $q.defer();

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

        return deferred.promise;
    };

  return {
    getMessages: getMessages
  };

});

和我在多个控制器中使用这些数据。

And I use these data in multiple controllers.

function ControllerA($scope, myService) {
    $scope.message = myService.getMessages();
    $scope.updateMessage = function(){
        $scope.message = 'Hello Max';        
    };
}

function ControllerB($scope, myService) {
    $scope.message = myService.getMessages();
    $scope.$watch('message', function(){
       // 'Hello Max'
    }, true);
}

我想更新每个控制器中的数据,但是当我更改ControllerA的$ scope.message,它不火的ControllerB的变化。

I would like to update the data in every controller, but when I change the $scope.message in the ControllerA, it doesn't fire a change in the ControllerB.

编辑:的事情是,我想尽量避免使用$广播和$的

The thing is that I would like to avoid using "$broadcast" and "$on".

任何想法?

下面是一个的jsfiddle: http://jsfiddle.net/Victa/McLQD/

Here's a jsfiddle: http://jsfiddle.net/Victa/McLQD/

推荐答案

您可以使用 $广播广播事件的 rootScope ,并使用 $关于定义监听器来听这个特定的事件。

You can use $broadcast to broadcast an event to the rootScope and use $on to define listener to listen to this specific event.

function ControllerA($scope, myService, $rootScope) {
    $scope.message = myService.getMessages();
    $scope.updateMessage = function () {
        $scope.message = 'Hello Max';

        $rootScope.$broadcast("HelloEvent", {
            msg: $scope.message
        });
    };
}

function ControllerB($scope, myService, $rootScope) {
    $scope.message = myService.getMessages();

    $rootScope.$on("HelloEvent", function (event, message) {
        $scope.message = message.msg;
    });
}

更新:

我给你更新你的问题之前上述溶液。如果你不想使用$广播或$,您可以通过共享对象 $ rootScop 电子像这样

I got the above solution just before you updated your question. If you don't want to use $broadcast or $on, you can share the object via $rootScope like this

function ControllerA($scope, myService, $rootScope) {
    $scope.message = myService.getMessages();
    $scope.updateMessage = function () {
        $scope.message = 'Hello Max';
        $rootScope.message = 'Hello Max';
    };
}

function ControllerB($scope, myService, $timeout, $rootScope) {
    $scope.message = myService.getMessages();

    $rootScope.$watch('message', function (oldV, newV) {
        if(oldV === undefined && oldV === newV) return;
        $scope.message = $rootScope.message;
    });
}

<大骨节病> 使用广播演示
<大骨节病> 演示,而无需使用广播

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

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