0

I'm making a fairly trivial notification system where I want a main menu (outside ng-view) to display the last activity of the user, from what I've read it looks like a service is best used to communicate between controllers. How should I detect when something happens in controller A immediately from controller B. Should I $watch the variable of the service? Or is there an easier way to do this? Or given should I just have a root scope variable and $watch and change that with the controllers?

coffee.isGood
  • 141
  • 1
  • 4
  • 11

3 Answers3

2

You should use $broadcast and $on methods. Here's a good example found on the internet

Also, there is no more an issue with $broadcast over $emit in recent versions of angular, because $broadcast runs as fast as $emit.

Don't use $watch for this because it will create a lot of events ( angular has also a limit of 10 rerun iterations to prevent deadlock ).

The watch listener may change the model, which may trigger other listeners to fire. This is achieved by rerunning the watchers until no changes are detected. The rerun iteration limit is 10 to prevent an infinite loop deadlock.

Read more here

Cosmin
  • 2,184
  • 21
  • 38
0

$watch will trigger everytime your variable change. Your can use $emit or $broadcast with $on for a less regular event. This can be done in a factory : how to emit events from a factory

Community
  • 1
  • 1
Komo
  • 2,043
  • 1
  • 22
  • 35
0

Could store something in the global $window and create a watch expression on it, that is just off the top off my head, might be a better way to do it.

Also take a look at this as it is like the sort of thing you need to do:

Share data between AngularJS controllers

Community
  • 1
  • 1
rtn
  • 2,012
  • 4
  • 21
  • 39