Controller communication in AngularJS

Quite often there is a need to pass data from one controller to another. This is relatively easy if we need to pass data from child to parent controller, but not so straight forward when controllers are not in that relationship.
Still, there’s quite a few ways of achieving that, differing in ease of implementation (though none are hard), performance and ease of maintenance.

Angular offers emit/broadcast/on methods on a scope, which are a lot like events in say C#, but they only broadcasted up and down in scope inheritance, so if you need to share data with sibling or some random controller in your app you need to jump through the hoops.

Say you have controllers A, B and C, where C is parent to both A and B. You can either emit event from A, catch it at C, and rebroadcast down to B:

plunk

You can use a rootScope, and emit and catch on rootScope alone:

plunk
Arguably thats a better way, you end up having a single spot for event dispatching, so it’s easier to maintain.

Another way, which we used, was to create a service which would expose an empty object, and use that object as a data bag.

If you just need to share data – you will create a property on that object and be done with it:

plunk

If you need to replicate an event – you can put a watch on that property. May not be the most performant solution, but on smaller apps shouldn’t matter.
plunk

Another way, slightly more complex to setup (if you write it from scratch), but also more flexible, is to have a real pub/sub service. Gives a lot more control over the lifetime of an event and attached listeners.

Here’s a plunk, but in short the interface would look like this:

Leave a Comment

Your email address will not be published.