How do I create a custom event in an AngularJs service

rmg.n3t picture rmg.n3t · Jun 9, 2014 · Viewed 59.6k times · Source

I am working on an AngularJs project. I have a service which sets and removes events on some buttons. This service is utilized by another service which I do not want to interact directly with the buttons. However I would like a button click event to be filtered up through the first service and handled in the second one. Since I don't want the second service to be aware of the buttons, I figure I will need to create a custom event in the first service. How can I create a custom event and fire it when a button is clicked?

Thanks in advance.

Answer

Chancho picture Chancho · Jun 10, 2014

If you want to send an event between services/directives use broadcast:

$rootScope.$broadcast('buttonPressedEvent');

And recieve it like this:

$rootScope.$on('buttonPressedEvent', function () {
             //do stuff
        })