AngularJS - Communicating Between Controllers

By: simpulton

314   34   106951

Uploaded on 05/30/2012

This video tutorial covers communicating and sharing state between controllers using a shared service and $rootScope.

You can grab the code here:
http://jsfiddle.net/simpulton/XqDxG/

With a BONUS fiddle using a directive
http://jsfiddle.net/simpulton/GeAAB/

If you have any technical questions check out the awesome mailing list here:
https://groups.google.com/forum/?fromgroups#!forum/angular

Comments (2):

By anonymous    2017-09-20

Each controller has it's own scope(s) so that's causing your issue.

Having two controllers that want access to the same data is a classic sign that you want a service. The angular team recommends thin controllers that are just glue between views and services. And specifically- "services should hold shared state across controllers".

Happily, there's a nice 15-minute video describing exactly this (controller communication via services): video

One of the original author's of Angular, Misko Hevery, discusses this recommendation (of using services in this situation) in his talk entitled Angular Best Practices (skip to 28:08 for this topic, although I very highly recommended watching the whole talk).

You can use events, but they are designed just for communication between two parties that want to be decoupled. In the above video, Misko notes how they can make your app more fragile. "Most of the time injecting services and doing direct communication is preferred and more robust". (Check out the above link starting at 53:37 to hear him talk about this)

Original Thread

Submit Your Video

If you have some great dev videos to share, please fill out this form.