Explain Codes LogoExplain Codes Logo

Share data between AngularJS controllers

javascript
angularjs
services
real-time-updates
Nikita BarsukovbyNikita Barsukov·Mar 6, 2025
TLDR

All AngularJS controllers can share data through a service. Thanks to AngularJS services being singletons, they are naturally designed to become a common data source. Just, create a service to stash the data and inject it in places it is needed.

// Service to hold and manage shared data. Best to always keep your data stashed carefully! app.service('SharedData', function() { var data = {}; return { get: function() { return data; }, set: function(newData) { data = newData; } }; }); // Use SharedData in Controller A to stack data. Stack them high! app.controller('CtrlA', function($scope, SharedData) { SharedData.set({ shared: 'info' }); }); // Access same stack of data in Controller B. No peeking! app.controller('CtrlB', function($scope, SharedData) { $scope.info = SharedData.get(); });

And Voila! CtrlA and CtrlB now share a synchronized state through SharedData service.

Sharing with AngularJS – Additional Techniques

This section covers more patterns for sharing data among AngularJS controllers using services, $watch, and even $stateParams!

Real-time LaTeX Data Binding with ng-model

With ng-model, we can bind input data onto the $scope. This yields real-time updates in your views.

app.controller('CtrlA', function($scope, SharedData) { $scope.sharedData = SharedData.get(); $scope.updateData = function(newInfo) { // Update scope data and push it to gluttonous service $scope.sharedData.info = newInfo; SharedData.set($scope.sharedData); }; });

And in HTML:

<input type="text" ng-model="sharedData.info" ng-change="updateData(sharedData.info)">

Employing $watch in Complex Structures

In complex applications, $watch comes to our rescue for detecting data changes. Albeit, it is advisable to use direct methods in simpler instances for better performance. It's like having a security guard for your data. 😎

app.controller('CtrlA', function($scope, SharedData) { $scope.$watch(function() { return SharedData.get(); // Our security guard in action! }, function(newValue, oldValue) { if (newValue !== oldValue) { // Data has changed! $scope.info = newValue; } }, true); });

Sharing Data Across Routes with $stateParams

Sharing data through URL parameters is a breeze using $stateParams combined with ui-router.

app.controller('CtrlA', function($scope, $stateParams, SharedData) { // Let's assume `info` is the URL parameter we want SharedData.set({ shared: $stateParams.info }); // Data on a field trip! });

Improving Communication with $broadcast and $emit

AngularJS provides us efficient event-based communication tools like $broadcast and $emit.

// Parent controller decides to light up a signal $scope.$emit('dataUpdated', newData); // Child controller is always on the lookout for signals $scope.$on('dataUpdated', function(event, data) { // A signal has been sighted! Update local scope with new data $scope.info = data; });

Additional Techniques for Mastering Sharing with AngularJS

This section discusses other crucial topics like managing shared data lifecycle and maintainable code writing practices.

Good AngularJS citizens destroy shared data appropriately when navigating away from routes. Also, you should retain shared data while hopping onto child route paths.

app.controller('CtrlA', function($scope, SharedData, $rootScope) { var killSwitch = $rootScope.$on('$destroy', function() { SharedData.set({}); // Time to hit reset! }); $scope.$on('$destroy', killSwitch); // Let's keep things clean here. });

Code Maintenance

// Adviced! Do not touch `$rootScope`. Swear on your keyboard!

Organize your code neatly using direct methods within the factory to make it maintainable for complex and larger applications.