Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  • Overview
  • Transcript

1.2 Sharing Data Between Angular Controllers

In this lesson, I'll show you some simple techniques for sharing data between Angular controllers. Controllers don't share scope, so they can't share data between them without a bit of extra work. I'll demonstrate a couple of ways in which controllers can pass data to each other with services, and also a way to pass data as a parameter to the state for UI-Router.

Code Snippet:

Here's an example of a service that allows an array of results data to be shared between controllers.

If you want to pass data as a state parameter to UI-Router, you can do it with a link like this:

You then declare this pet param to a state in the $stateProvider.state configuration and access it in your controller with $stateParams.pet.

1.Sharing Data Between Angular Controllers
2 lessons, 11:58

Free Lesson
1.1
Introduction
00:42

1.2
Sharing Data Between Angular Controllers
11:16


1.2 Sharing Data Between Angular Controllers

[SOUND] Hello everyone, this is Reggie Dawson. Welcome to the Sharing Data Between Controllers Coffee Break Course for Touch Plus. Angular JS patterns that allow developers to quickly build large scale web apps. If you have used Angular, you will be familiar with setting up controller and wiring in services through dependency injection. This has been one of the key features that has attracted developers to Angular. Often when we have an app, we need a way to pass data between controllers. Whether it is using information or an ID we need to access and record in a data, there are time when we need to pass information between on controller and another. Fortunately, it is much easier to pass data between controllers than you think. If we are using angular, then you are probably making use of services. No doubts, perhaps you have wired up a service to wrap up public APIs, such as YouTube or Instagram. This is the desired usage of services, and perfectly fine. Beyond that, however, we can use services to provide and pass data between controllers. As you know, controllers don't share scope and pass data unless they are nested within one another. This becomes a problem when we need to share data between two separate templates. Let's set up a small project to demonstrate some ways we can share data between controllers. Create a folder to hold our project and navigate to it in your command line. It is quick and easy to setup an Angular project if we use Bower. If you don't have Bower installed it's not a problem as long as you have Node JS installed. After that we will install Angular, 'bower install angular', will install Angular to our Bower components folder. Then we will install angular UI router. This will install the Angular UI router, which is the preferred routing used by a lot of Angular developers. After that, we can create a JS folder. Inside this folder, we will create a file called app.js. Then we're going to create an index.html, home.html, and results.html files. First, we will setup index.html. In this file, we have ng-app which is the name of our Angular application. Then we have our script reference for Angular and Angular UI router. Since we installed with Bower, we are referencing them from the Bower components folder. After that we have our script reference to app.js which is where we will be setting up the app. And finally in the body we have a div with ui-view attached. UI view is where UI router will place our templates on the page. After that let's go our home.html page. Since this is going to be loaded as a template, we don't have to put much into this file. First we have added a button with ng-click attached. This button will execute the settext function when it is clicked. Then on the text input we have an ng-model of value one. This provides the value in the input to our controller. Finally, we will setup our results.html page. This page is even simpler that our first template. Here we are just displaying data from our controller in an h1 tag. Then we set up a link that gets us back to the homepage. You will notice that the link is using ui-sref. This is a feature of Angular UI router that allows us to change states. Now let's go to app.js. The first thing we will add to app.js is our module definition. Here we are defining a module with the name of myApp, which corresponds to the ng.app that we see up in our index.html. We have also injected the UI router service into our app. Next we will set up our config block. This block has the state provider and URL router provider services injected. These services, which are part of angular UI router, will be used to set up our routing. Here we are setting up our states. States can be thought about as pages, but much more information than just the page is associated with the state. For example, as you can see here our home state has a URL, a template and a controller configured. Therefore when we access the home state, we will be using the specified resources. We also have a urlRouterProvider.otherwise, which will navigate to the home state when there is no state specified. As a result, when we launch our app we will navigate to the home state. After we have our config block done we're going to set up our service. Here we are creating a service called resultService. First we will add a variable. This is the variable that we will use to hold our data, then we can create an object to hold the methods that our service will offer. This is the basic pattern we will use to pass data to other controllers. First we have the setResult method which will set its input as the result variable. Then after that in order to access this data, we will use the getResult method to return the data. All we need to do to access information stored is to use this method in a controller. This is definitely a simple solution, but very powerful once you consider this information is available anywhere in you app. The last thing we need to do in our service is return our result service. Then we will set up our first controller. This is the controller that we have configured to be attached to the home state. It has dependencies of scope, result service, and state. Scope is standard and should be included in all controllers. It allows us to tie data into our controllers and pages. Result service is our injected service we just set up. State is going to allow us to change states inside of our controller. Here we are using scope to make our function available to our HTML page. Remember the ng-click on the home.html page? Well, this is the function that it'll execute. Inside this function we are using the resultService setResult method. The supplied argument is value one which is the NG model we set up on the text input. As a result what we type in the input will be sent to the setResult method. After that we will navigate to the resultState with state go. The last thing we need to do is to set up the second controller. This controller only needs to display the saved data, so all we're doing is grabbing the result from our service and setting it in value two. That's all we need to do to set up a simple project that demonstrates sharing between angular controllers. Let's save and preview our project. I'm using Cloud 9, and all I have to do is open the index.html file and click run. After that I click on the preview link. Bear in mind if you are directly on your machine, you may need a web server as some browsers will not let you run your JavaScript locally If we type something in the text input we will be taken to the results page which will display what we typed. After that we can navigate back. Now this could find its uses but it's kind of limited. What if we wanted to save a list of data? In that case, it is very easy to reconfigure our app to use an array. In our service, let's change result to an array. Then we just need to make a small change to the setResult method. We are now using the push method to add to the array that we have setup in our service. Now if we save and preview. Now when we add something it is saved in an array. If we go back and add more data, it will be added to the array as well. It would be a simple thing to add a way to remove items from this array, and as such this could be useful to an application. We also could have used JavaScript objects in our service as well to handle complex data with multiple fields. It all depends on what our needs are for our app. One thing to bear in mind is that this solution is not perfect. If we refresh our page, the data will be reset. So although we can share data this way, we need some way to make the data persistent. This could be as simple as using local storage, or even writing to an external database. Finally, I wanna show you one more way to share data between controllers. This way does not involve services and as a matter of fact, won't even need a service this time. This method is only for very simple data but I find it very useful when choosing a record from a list of data. For example, let's say we had a list of widgets for sale. If a user clicks on a widget, then they should be taken to the page for that widget. When navigating, we need a way to pass what widget was chosen. Normally, the widget has some defining ID that we can use to access it. So in this case, we need to pass this ID. That's where this method of passing data between controllers comes in. First in home.html, remove everything between the divs and replace it with this. Inside these divs we are using ui-sref to change states, but you will notice something in parentheses after the state. This is what's called a state parameter, or state param for short. Here we are setting the pet state param. Normally we use state params to pass information to URLs, but we're gonna use it to pass data through a link. Next we will go to the results.html page. On this page we will replace the tag inside of our h1. We have replaced value 2 with mypet. Then finally let's app.js. First we will add a param to our result state. By setting params to null, we are going to use the params to pass some information that is not part of the URL. Then I'm going to fold up our service to get it out of our way, although you can delete it if you like 'cuz we're not going to need it for this example. Then we can get rid of everything in controller one. We're also going to remove all dependencies except scope. Then we will add some data for our page. Here we are setting some basic strings. I purposely set the name of the variables to be different from the actual values so we can be sure what is being passed in our templates. Then in controller two we will remove the result service from dependencies and add state params. Then remove what's inside your second controller and replace it with this line. Here we are using the state params passed in from the links to set the mypet variable. As you know we set this variable to display on the results page. The idea is when we click on the link the state param will be passed over to the results page. Let's save and preview. If we click on a link it should display what we clicked. As you can see, the scope data we used is passing the value through to controller two. Again, this is limited in use, but as a way to pass an idea across to access data in a database, it is perfect. This is my go to method when I need to return a record from a list. Of course this is not its only use and I am sure that you could come up with something that I never thought of. Now you should understand how we can share data between controllers in Angular. Hopefully knowing this gives you some ideas on how you can use these concepts in your own apps.

Back to the top