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?
-
I am new to AngularJS, but maybe you should take a look at `emit`/`broadcast` functionality for loose coupling of your controllers – Maciej Dobrowolski Mar 25 '15 at 10:39
3 Answers
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

- 2,184
- 21
- 38
$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
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: