Skip to content Skip to sidebar Skip to footer

Angular: Update Service And Share Data Between Controllers

I'm using a service to grab some data from an API: angular.module('myApp', []) .factory('myService', function($q, $timeout) { var getMessages = function() { var deferre

Solution 1:

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

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

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

functionControllerB($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

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

functionControllerB($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 broadcastDemo without using broadcast

Post a Comment for "Angular: Update Service And Share Data Between Controllers"