4. AngularJS Video Tutorial: Sharing Data Between Controllers
If AngularJS Controllers are the glue of an application, how do they communicate and pass data around? This introduction to service factories will shed some light on that question.
John Lindquist: Now, let's talk about sharing data between controllers.
Let's add a bunch of white space here just to show that these are completely separate controllers.
Now, this is working. You can see that all of these are being bound and updating to each other but the reason that's working right now is because you have a data message model defined there.
If we delete that and we run this again, first will not bind to second. You're going to see they're separated now because this data message is inside the scope of this first controller and this data message is inside the scope of the second controller and there was no parent scope for them to grab that data model off of.
What we're going to do here to share the data instead of creating a parent scope and inheriting from it is creating something called a service. The first step you need is we actually need to define our first app. It will be an angular module and we'll just call it "myApp" and we'll have no dependencies. That's just kind of the syntax we use. We'll talk more about this stuff later.
Basically, you say this will be myApp and that this guy links up to this name here. Just make sure those match and you're fine.
From there, once we have myApp, we can create a factory to create our service. We'll just call this service "Data." Capitalizing the first letter is kind of a convention you'll see. Then, we'll create a function which will return an object with the message called, "I'm Data from a service."
Now, we can inject this Data. Again, we'll be using this string to inject into here. We can inject that data into the first controller and say scope data is Data. Hit refresh. You can see that we now get our data into this field and this is bindable and all we have to do to share it with the second controller is do the exact same thing. Scope data is Data. Hit refresh.
You can see that both of these are getting data from the service and they're both bindable. That's how you share data between controllers.
Basically, you create a service using this factory, you return whatever sort of object you want to use with. We'll talk about building up APIs for services and that's for the stuff later on. But once you've defined a service and this object, you can just inject it by using this data lookup and it will be ready for any of your controllers to use and any of the scopes to watch for changes on.
You can see that these are completely separate. There's no root scope or scope inheritance going on there. You're simply injecting this service and this object into each controller.