0

To share data between controllers it is common to use service.

I found that using $rootScope.$broadcast is really convenient if the data I have to share is a [] or an {}.

For me the advantage of using broadcast is that you don't have to use watcher to check if the data has been loaded into the service. Also less code to write.

So my questions are :

  • Is it ok to use $broadcast
  • Is there some inconvenient using $broadcast

Here is some examples using both "techniques" to show what I mean.

Example using $rootScope.$broadcast

// controller is registering 'list-loaded'
angular.module('myApp').controller(
    'ControllerOne'
            ['$rootScope','$scope',
                function ($rootScope, $scope) {

                    // the data
                    $scope.data = {
                        list : ["foo","bar"]
                    }
                    // sending the event with the data
                    $rootScope.$broadcast('list-loaded', { list: $scope.data.list });
                }
            ]
);

//controller is listening for 'list-loaded'
angular.module('myApp').controller(
    'ControllerTwo',
            ['$rootScope','$scope',
                function ($rootScope, $scope) {

                    // empty data
                    $scope.data = {}

                    // when the event is received we set the data
                    $scope.$on('list-loaded', function(event, args) {
                        $scope.data.list = args.list;
                    });
                }
            ]
);

Example using service

// the service
angular.module('myApp').factory(
    'Service',
        [ 

            function() {
                // the data to be shared
                var list = []

                return {
                    setList : function(pList){
                        list = pList;
                    },
                    getList : function(){
                        return list;
                    }

                };
            }
        ]
);

//controller is setting list into Service
angular.module('myApp').controller(

    'ControllerOne',
            ['$scope', 'Service',

                function ($scope, Service) {

                    // setting the data to service
                    Service.setList(["foo","bar"])
                }
            ]
);

//controller is getting list from Service
angular.module('myApp').controller(
    'ControllerTwo',
            ['$scope','Service',

                function ($scope, Service) {

                    // getting the data from service
                    $scope.data = {
                        list : Service.getList()
                    }
                }
            ]


);
ram1993
  • 979
  • 1
  • 9
  • 13
Merlin
  • 4,907
  • 2
  • 33
  • 51
  • 2
    far simpler to manage a service than lots of events. A service is absolute and always exists...events require that both broadcaster and listener are in existence at same time. Also inheritance of objects/arrays in service mean not much code needed to bind them – charlietfl Oct 13 '16 at 17:14
  • Where you are going wrong in service is breaking reference to original `list` array by overwriting `list` variable with a new reference – charlietfl Oct 13 '16 at 17:19
  • It isn't about sharing data, it is about messaging. If one of the controllers was instantiated later, it won't get the message. Global bus was proven to be a lousy pattern in most cases where it may be used. No, it is not ok, and yes, there's something inconvenient. In your particular case it defies the purpose. Scope events aren't tied to digests and `$scope.data.list` won't be updated in view. – Estus Flask Oct 13 '16 at 17:34
  • Usually you use $broadcast to catch an event the controller wouldn't otherwise know about. Say you have a dropdown menu in controller x that has dynamic values that are different when the user is authenticated vs non-authenticated. If a login happens, you can broadcast that event to controller x and know to refresh the dropdown. – Taylor Ackley Oct 13 '16 at 18:00
  • I would also like to add that you can reuse a service, but for `broadcast` and `emit`, it's not possible. Also, all of your scopes have a given order, so you need to know this order to know when to use which. Finally, John papa suggested that you should stop using `$scope`. –  Nov 10 '16 at 15:08

0 Answers0