0

We're implementing a widget screen that consists of multiple widgets/modules:

  • Products: Lists products
  • Product Details: Loads product details from server once selection in "Products" changes.
  • Related Products: Loads related products from server once selection in "Product" changes.
  • Compare: Does some stuff on the server once "Compare" in "Product Details" is clicked.

Widget Screen with 4 Widgets

Sounds pretty easy, right? Our problem is, that we cannot find a good solution how the components should communicate with each other. They should be as loosely coupled as possible. So I don't want the "Products" widget to know that the "Product Details" widget and the "Related Products" widget exist. Maybe some widgets are not even displayed on the screen right now (so nothing should happen there).

The only solution that came to our mind was to use $rootScope.$broadcast and $rootScope.$on to work with events such as "ProductSelectionChanged" or "CompareClicked".

Unfortunately $rootScope.$broadcast seems to cause performance issues, as far as I understood: What's the correct way to communicate between controllers in AngularJS? AND the proposed solution by Christoph using $rootScope.$emit does not work in IE8.

Should I just use $rootScope.$broadcast? Or is there a better solution?

Thanks for your help!

Cheers Michael

Community
  • 1
  • 1
Michael Hunziker
  • 2,659
  • 3
  • 22
  • 26
  • I think the only way for this to work is through a `$broadcast`. The reason being that you need to have knowledge of the details somehow...without that sort of explicit dependency, I don't think there is another solution. – gonzofish Feb 10 '14 at 15:35

2 Answers2

1

I do not claim that this is the best solution but I encountered the same problem of communication between my components and the $scope.$broadcast() performance issue. With my team, we decided to develop a small PubSub service. It is very simple and can communicate events quickly, with parameters.

If you want to give it a try, it's available here: angular-pubsub

glepretre
  • 8,154
  • 5
  • 43
  • 57
1

You can use messaging like they point out up there, not a bad solution but it can get messy if there is too much communication. In our case we wrap it in a RequestNotification control and define some const ID's (see RequestNotificatinService)

http://lemoncode.net/2013/07/31/angularjs-found-great-solution-to-display-ajax-spinner-loading-widget/

Another approach is to define an outer directive (e.g. contains common data or...) and request it in the inner directives (something similar at what we do when we request ngmodel in a custom directive)

I think a good sample about how this work can be found here: http://jaysoo.ca/2014/01/20/semantic-angularjs-directives/

Braulio
  • 1,748
  • 14
  • 23