ArticleZip > Angularjs How Can I Pass Variables Between Controllers

Angularjs How Can I Pass Variables Between Controllers

In AngularJS, passing variables between controllers is a common requirement that often arises when you're working on building interactive web applications. Fortunately, AngularJS provides us with a straightforward way to achieve this through services and $rootScope. Let's dive into how you can effectively pass variables between controllers in your AngularJS projects.

1. Using Services:
One of the most popular and recommended ways to pass data between controllers in AngularJS is by utilizing services. Services act as singletons in AngularJS, which means they maintain their state throughout the application lifecycle. You can store your shared data in a service and access it from any controller that injects that service.

Below is an example demonstrating how to pass data between controllers using a service:

Javascript

angular.module('myApp').service('dataService', function() {
       var sharedData = {};

       return {
           getData: function() {
               return sharedData;
           },
           setData: function(data) {
               sharedData = data;
           }
       };
   });

2. Using $rootScope:
Another way to share data between controllers in AngularJS is by leveraging the $rootScope object provided by AngularJS. $rootScope is the parent scope for all AngularJS scopes and can be used to store and retrieve global data that needs to be shared between controllers.

Here's an example illustrating how to pass variables between controllers using $rootScope:

Javascript

function Controller1($scope, $rootScope) {
       $rootScope.sharedVariable = "Hello, world!";
   }

   function Controller2($scope, $rootScope) {
       $scope.receivedData = $rootScope.sharedVariable;
   }

3. Using $broadcast and $on:
If you need to pass data between controllers not connected by a parent-child relationship, you can make use of AngularJS events system. You can broadcast an event with the data from one controller and listen for that event in another controller to retrieve the data.

Here's a simple demonstration of using $broadcast and $on to pass variables between controllers:

Javascript

function Controller1($scope, $rootScope) {
       $rootScope.$broadcast('dataPassed', { message: 'Hello, world!' });
   }

   function Controller2($scope, $rootScope) {
       $scope.$on('dataPassed', function(event, data) {
           $scope.receivedData = data.message;
       });
   }

If you're working on a more complex AngularJS application with multiple controllers that need to share data, using services or $rootScope is the way to go. Remember to design your application structure carefully and consider using services as a clean and maintainable solution for passing variables between controllers in AngularJS.

×