In AngularJS it’s very common to have more than one controller in a single page. If you use components or directives, for example, you will end up with several controllers in a single page, with each controller having its own responsibilities. This is great because we can separate concerns and turn our code more reusable, sustainable and easy to maintain and grow.
Imagine now that we have two or more components or routes and we want to share some data between them. How can we communicate between the controllers? Simple: using Services.
Services are a nice and clean way to achieve this. Since services are singletons they can be injected in any place you want the shared data.
Let’s start with an example. Here, we have two controllers.
The first controller will hold a list of a shopping list. The second controller will be responsible for the input buttons for adding new items to this list. Note that we will separate the concerns. One controller will be responsible for displaying the list and the other controller will be responsible for adding items for this list.
The code is very simple:
Shared Service:
app.service("myService", [() => { const list = ["Cheese", "Meat"]; function getList() { return list; } function addItem(item) { list.push(item); } return { getList: getList, addItem: addItem } }]);
The List Controller:
app.controller("ListController", ["myService", function(myService) { const vm = this; vm.list = myService.getList(); }]);
Input Controller:
app.controller("InputController", ["myService", function (myService) { const vm = this; vm.addItem = (item) => { myService.addItem(item); } }]);
Putting all together:
Note that we didn’t need to setup additional watchers because we are holding the reference for the list array. Since the ng-repeat already add its own watcher’s this code works without any problems.
Any questions? Leave a comment below and we’ll get to you ASAP!
About the author
Guilherme Severo is a Software Engineer at Poatek.