繁体   English   中英

Angular:更新服务并在控制器之间共享数据

[英]Angular: Update service and share data between controllers

我正在使用服务从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
  };

});

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

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中的更改。

编辑:问题是我想避免使用“$ broadcast”和“$ on”。

有任何想法吗?

这是一个jsfiddle: http//jsfiddle.net/Victa/McLQD/

您可以使用$broadcast将事件$broadcastrootScope并使用$on来定义侦听器以侦听此特定事件。

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

更新:

在您更新问题之前我得到了上述解决方案。 如果你不想使用$ broadcast或$ on,你可以通过$rootScop e这样分享对象

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

使用广播 演示而不使用广播 进行 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM