Service Portal: Widget Communication

For the most part, widgets on the service portal are very self-contained. Widgets have their own scope, and most of their operations are contained within that scope. However, when developing custom widgets in the Service Portal, you may have the need to pass information from one widget on your page to a second widget on that same page. This can be done using a few angular methods: $broadcast, $emit, and $on. Let’s talk about what these methods do.

$broadcast and $emit are both methods that allow you to raise an event in your widget. The difference between the two is the direction of the event. $broadcast sends an event downwards from parent to child controllers, while $emit sends an event upwards from the current controller to all of its parent controllers. You can then subscribe to an event using the $on event handler.

Let’s walk through an example. Say you have “Widget 1”. Widget 1 will allow the user to click a button. Once the button has been clicked, the widget will use $broadcast to pass an object to “Widget 2.” So let’s look at what the client controllers for both these widgets would look like.

Widget 1

Here, we have set “c.onBtnClick” to a function that creates an object. Then, at the end of the function, we call “$rootsScope.$broadcast” which will then broadcast our object (the second parameter) to other widgets on the page. Any widgets that are listening for “myEvent” (first parameter) with $on will now pick up this object being broadcasted.

Note: The button would include an ng-click directive for the function “onBtnClick” inside the HTML template. This is how the function would be called.

Widget 2

Our second widget would also be fairly simple. Here, we simply call $rootScope.on. The first parameter is the name of the event we are listening for, and the second is a callback function that will run when the event is triggered. So in this example, widget 2 is able to log properties from the object passed by Widget 1.

And there you have it, this is how you can pass information between two widgets in the Service Portal. This was a simple example, but the logic can be applied to many situations. One common one is filtering data in a widget based on another. You can also then perform server-side operations in your widget based on the passed data if the situation calls for it. I hope this was helpful, and good luck with your widgets!