Home / Angular / AngularJS – Access $broadcast, $emit, or $watch from within a service

AngularJS – Access $broadcast, $emit, or $watch from within a service

There are scenarios where you might have a service that shares logic between a few directives and you might need to access specific $scope methods, like $broadcast or $watch that are normally only available on $scope and not in the service. Most people in this case will use the $rootScope as a scapegoat, however this unadvised. Reason for that is that it will cause a leak when the directive gets destroyed. In normal case when the directive $scope is used, Angular knows what methods are bound to for example watchers since they are on the same $scope. When the directive gets destroyed, Angular is able to clean those references without the chance of memory leaks.

So, if we cannot use $rootScope, how do we access the $scope we want in the Service? Lets take a look at the following codepen sample.

NOTE: There are simpler ways for the two child directives to communicate with each other, but the sample is just to clarify how you can access the $broadcast from within a service. Actual usage for this will emerge when you have more complex nested isolated directives which might also include some 3rd party directives.

See the Pen:

In the above sample we see that the parent directive is the only one that has a broadcaster function that calls its $scope.$broadcast. The parent directive set this broadcaster function in the broadcastService using the setBroadcaster methode. From that moment on, both of the child directive can broadcast an event using the broadcastService.broadcast method every time you click on them. Doing so, will make the parent directive execute the broadcasting of the event. In this way the parent directive is the only one who actually broadcast the event, even if it is the child that call the broadcastService.broadcast method.

 

Interested joining BVA Auctions?

Take a look to our vacancies

About Mario

Mario is a FrontEnd webdeveloper/designer interested in highly interactive webapplications with focus on JavaScript (native, AngularJs, UI Bootstrap, AngularStrap, Dojo, Scriptaculous & Prototype), CSS (native, LESS, Bootstrap.css) and HTML

Leave a Reply

Your email address will not be published. Required fields are marked *

css.php