Using Events to Communicate Between Widgets

Following the principle of “separation of concerns”, it is good practice for your portal or application to be made up of self contained functional components, also known as widgets in Service Portal. However sometimes these widgets need to communicate with one another. Thanks to Angular.js this can be accomplished through the use of $broadcast, $emit, and $on methods.

$broadcast and $emit allow you to raise an event in your widget. The difference between $broadcast and $emit is that the former sends the event downwards from parent to child controllers, while $emit sends an event upwards from the current controller to all of its parent controllers. Both methods are available on $scope and $rootScope. You can subscribe to an event using the “$on” event handler.

In this example we will create two widgets that interact using $broadcast and $on.

Widget #1:

Create two buttons that upon click, will $broadcast an event called “customEvent” and pass an object.

HTML:

Client Script:

Widget #2:

Listen for the “customEvent” event, and when triggered, the callback function will update the text.

HTML:

Client Script:

The final results should look like this:

videotogif_2016-11-22_10-48-41

14 comments

    1. $scope will not work, because each widget has isolated scope, but rootScope can be accessed from both of them 🙂

      1. To communicate between two pages, simply pass the data using URL parameters. If you need to pass lots of data you could look at using an Angular Service

  1. Hey Nathan,

    I am working on a service catalog requirement on the sc_cat_item page. The sc_catalog_item widget that is used on the page is cloned and customized. In addition to the sc_catalog_item widget, there is an embedded macro widget on the sc_cat_item page. This macro widget has a checkbox.
    When the sc_cat_item page is rendered, in some situation, the submit (order now) button will be disabled. When that happens, the checkbox in the embedded macro widget should be clicked to enable the submit button. I am thinking that broadcasting from the embedded widget and listening from the sc_catalog_item widget will be the way to go. But, unsure how to accomplish this.
    Could you please guide me through this?
    Thank you very much.

Leave a Reply

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