John, in Y031 you mention the following:
For example when publishing and subscribing events using $emit, $broadcast, or $on consider moving these uses to a factory and invoke from the controller.
Could you expand a bit on how to implement this? A code sample would be nice!
I wondered this too and found the following stackOverflow question/answer: http://stackoverflow.com/questions/14056874/how-to-emit-events-from-a-factory
I'm fairly beginner as far as angular goes, so if this is bad practice, someone please tell me. :)
I think it is also depending on whether you are in a pure angular project or a legacy/hybrid project.
i.e. you want to share same event inside and out side Angular framework
making the pub/sub into a factory make alternative implementation easier to replace $emit, $broadcast.
e.g. http://jonathancreamer.com/an-angular-event-bus-with-postal-js/
I'm too having some trouble understanding the following sentence from Y031:
Consider using $scope in a controller only when needed. For example when publishing and subscribing events using $emit, $broadcast, or $on consider moving these uses to a factory and invoke from the controller.
So the conclusion of the above sentence is to avoid broadcasts at all with the use of factories? If so, I'd suggest a different formulation.
I'm not thinking about inter-controller communication but rather of major state changes like login/logout. Since I possibly have to inform pretty much all components about that if feels like a proper task for a broadcast?
If I understand correctly, I think you are misunderstanding this @sebastianhaas. This passage in the style-guide is suggesting moving the usage of $emit
, $broadcast
, or $on
to a factory, not replacing the usage _with_ a factory.
Thanks for your answer @zachlysobey! Yes, but how would you achieve that? Lets assume I want to update values in a controller on certain broadcasts. If I move those $on
's to a factory, I'm wondering how to inform the controller again.
Let me clarify ... I had a confusing sentence in there. The point was to only use $scope when needed. Which is when you have to have a scope to handle the job. This includes broadcast or emit. Those are OK in the controller if, and only if, a message is what you need to send. But you may also want to consider other options too.
I was trying to be careful here because I want to discourage scope.apply in controllers too.
I removed the sentence.
Thank you very much!
Most helpful comment
great insight here http://stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs/19498009#19498009