4

I have nested controllers and need to astablish communication between the controllers.There are two ways I can think of achieving this:

  1. Have a central "PubSub" service that all the controllers can use to communicate. The disadvantage of this in my opition is that each controller can talk to any other controller and there is no meaning to the heirarchy.
  2. Another approach is that controller can only talk to his father and this children, as described is the image: enter image description here

So I need a separate communication channel for each heirarchy level. Not sure how to achieve this. I thought of making a service that provides a communication channel but how do I inject it to the relevant controllers??

Which solution is better and how do I implement the second solution is it's better? or maybe there are other solutions?

julius_am
  • 1,422
  • 2
  • 23
  • 42

3 Answers3

0

How about creating a map in a service, which will keep track of possible ways to communicate between controllers

so if you register for example scope of Controller 1, you can save ID of parent and children scopes and open a communication channel to these controllers only - you will emit events with particular ID of com. channel and it will be affecting only those controllers involved.

doodeec
  • 2,927
  • 19
  • 23
0

For approach 2, an option would be to use events.

To send an event downwards from the parent scope to child/descendant scopes, you could use $scope.$broadcast('myEvent', args) and in the child scopes, listen for the event using $scope.on('myEvent', function(event, args){...}).

Though it seems that all communications are downwards, if ever the child scope needs to send an event upwards to the parent/ancestor scopes, you can use $scope.$emit instead.

You can check this question: $scope.$emit and .$on angularJS on how to use $emit (upwards) and $on. It is similar to $broadcast (downwards).

Community
  • 1
  • 1
Kelvin Yong
  • 118
  • 7
  • broadcast, emit .etc don't prevent from child controller to talk to his grandpa controller... – julius_am Feb 05 '14 at 10:12
  • You are right. The top controller can broadcast downwards to all his children, grandchildren and so on. However the grandchildren can choose not to listen to the event too. Or if the grandchildren choose to listen to that event, check the args being passed to decide if he should process or ignore the event. – Kelvin Yong Feb 05 '14 at 15:53
0

Would you try use postaljs as message bus: http://jonathancreamer.com/an-angular-event-bus-with-postal-js/

You can use postal by publishing messages accross specific channels, In this way you can segregate your messages to things like root, root.leve1,root.level2 and subscribe to it with the wildcard topic. i.e: root*, root.level1, ...

pdorgambide
  • 1,787
  • 19
  • 33