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

Angular: Update service and share data between controllers

本文关键字:控制器 之间 共享 数据 更新 服务 Angular      更新时间:2023-09-26

我正在使用一个服务从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"answers"$on"。

有什么想法吗?

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

您可以使用$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,你可以像这个一样通过$rootScope共享对象

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

使用广播的演示不使用广播的演示