Sharing data between Controllers

AngularJS - 00001

In my AngularJS classes, I often get asked, “How do I share data between the controllers in AngularJS?”
Here, I’m going to describe best answers here.

1. Sharing Models Between Nested Controllers

You wish to share a model between a nested hierarchy of controllers.
Use Javascript objects instead of primitives or direct $parent scope references.

Our example template uses a controller MyCtrl and a nested controller MyNestedCtrl:

The app.js file contains the controller definition and initializes the scope with some defaults:

Play around with the various input fields and see how changes affect each other.

2. Services provide an easy way for us to share data and functionality throughout our app.

The services we create are singletons that can be injected into controllers and other services, making them the ideal place for writing reusable code.

In this example, we’ll be creating a service for storing messages, and two controllers, one for rendering a list of messages, and another for adding more messages to the list.

Let’s set up our angular module, and create our service and call it messages

Create and return and empty object called messages. This is the object that dependencies of this service will receive.

Create a property list on messages, and set it to an empty array. This is where we will be storing our messages.


Create a function add on messages that will add provided messages to our list.


Now that our service is ready, let’s create a couple controllers to make use of it.

Create a controller called ListCtrl that injects our messages service, and exposes the list from our service to our view.

Within a div that uses the ListCtrl that we just created, use the ng-repeat directive to display our list of messages.


The ng-repeat directive iterates over collections within our view, repeating the contents within the element where ng-repeat is used. Since our list of messages is currently empty, let’s create another controller to help us populate the list.

Create a controller named PostCtrl that also injects our messages service. This controller will also contain an addMessage function that uses the add function we made in our service.

Create a form underneath our list using PostCtrl

Set a newMessage within PostCtrl to get a default message, set newMessage to an empty string after calling message.add to clear out the input field after it’s been submitted.

View Code on GitHub

2 thoughts on “Sharing data between Controllers

Leave a Reply

Your email address will not be published. Required fields are marked *