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

Vic*_*Vic 4 javascript service factory promise angularjs

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

});
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

我想更新每个控制器中的数据,但是当我更改ControllerA中的$ scope.message时,它不会触发ControllerB中的更改.

编辑:问题是我想避免使用"$ broadcast"和"$ on".

有任何想法吗?

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

zs2*_*020 8

您可以使用$broadcast向该事件广播事件rootScope并使用它$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;
    });
}
Run Code Online (Sandbox Code Playgroud)

更新:

在您更新问题之前我得到了上述解决方案.如果你不想使用$ 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;
    });
}
Run Code Online (Sandbox Code Playgroud)

Demo using broadcast Demo without using broadcast