Sharing Data between Angular Controllers

Use a service to pass data between controllers. So why would we want to or need to do this. To understand that you first need to understand the ‘View’ and ‘Controller’ function of Angular. In Angular any $scope variables we update or change in our controller only live in that controller and in that view and will not persist when we route to a new view. With this in mind here are a few ways to persist that data.

First you can return the entire object from the service and then access its enumerable values directly in any controller that it is injected in. Second you can use functions to expose the individual values to your controllers.

Let’s start with the first method where we return the entire object to the controller. In this method our service will return an entire object that is the data you which to share between controllers. Then each controller can use its own internal functions to set or retrieve data from your object. This works rather well for small applications but can get a bit bulky in larger ones and can break DRY principles.

angular
.module('ClickedFactory', [])
.factory('ClickedFactory', ClickedFactory)
function ClickedFactory() {
const userInfo = {};
return { userInfo };
}

The second method for sharing data across controllers is to have your factory control the data object and only share its methods for accessing that data. In this method our service returns an object with functions for the controllers to use but does not directly share the data to the controllers. Instead the controllers use these shared functions to update and retrieve information from the services data structure.

angular
.module('ClickedFactory', [])
.factory('ClickedFactory', ClickedFactory)
function ClickedFactory($location, $http) {
const userInfo = {};
const setUser = function (data) {
userInfo.clicked = data;
};
const getInfo = function () {
return $http.get('http://localhost:3000/userinfo/' + userInfo.clicked);
};
return { getInfo, setUser };
}

There of course other methods for sharing data between controllers including $rootScope and stateparams that I will add to this blog when time permits. A quick comment on these is that the $rootscope is like a global store that can be accessed by any controller but like most global things can cause problems because of this. The stateparams is like a query string and involves adding information to your angular-route as you switch between views.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.