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?

1
  • I am new to AngularJS, but maybe you should take a look at emit/broadcast functionality for loose coupling of your controllers Commented Mar 25, 2015 at 10:39

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.