Angular: Update service and share data between controllers

后端 未结 1 1406
孤街浪徒
孤街浪徒 2021-01-06 08:50

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

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


        
相关标签:
1条回答
  • 2021-01-06 09:14

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

    Updated:

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

    Demo using broadcast Demo without using broadcast

    0 讨论(0)
提交回复
热议问题