Open In App

How to use $rootScope to store variables in Angular ?

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Angular, the $rootScope is the service that is the top-level for all the controllers in the Angular application. This exists over the entire application lifecycle and can also be used to store the variables that need to be accessed globally. $rootScope is a singleton object that is across the entire application.

In this article, we will see the proper use of $rootScope in Angular to store variables. We have added the two examples that represent the use of storing variables using $rootScope in different perspectives.

Steps to Configure the Angular Application

The below steps will be followed to configure the Angular Application to use $rootScope in Angular to store variables:

Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.

mkdir root-scope
cd root-scope

Step 2: Create the index.html file in the newly created folder, we will have all our logic and styling code in this file.

We will understand the above approaches with the help of suitable illustrations.

Using $rootScope Service

In this approach, we have directly used $rootScope to store the variable across multiple controllers. This approach uses the $rootScope service to create a shared variable (title) that is accessible over two controllers. Controller1 displays the initial title which is defined and stored using $rootScope and an approach description whereas Controller2 allows users to enter the input of a new value for the shared value. When the user clicks on the Update Title button dynamically the title is been changed using the $rootScope.title.

Example: Below is an example demonstrating the use of $rootScope directly in AngularJS to store variables.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>Angular $rootScope Example</title>
    <script src=
      </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 50px;
        }
  
        h1 {
            color: green;
        }
  
        h3 {
            color: blue;
        }
  
        input {
            padding: 10px;
            margin-top: 10px;
        }
  
        button {
            padding: 8px;
            margin-top: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
  
<body ng-controller="Controller1">
    <h1>{{ title }}</h1>
    <h3>{{ approach }}</h3>
    <div ng-controller="Controller2">
        <label for="sharedVariableInput">
              Enter Shared Variable:
          </label>
        <input type="text" 
               ng-model="sharedVariable"
               id="sharedVariableInput"
               placeholder="Enter text">
        <button ng-click="updateTitle()">
              Update Title
          </button>
    </div>
    
    <script>
        var app = angular.module('myApp', []);
        app.run(function ($rootScope) {
            $rootScope.title = 'GeeksforGeeks';
        });
        app.controller('Controller1', function ($scope, $rootScope) {
            $scope.approach = 
              'Approach 1: Using $rootScope Directly';
        });
        app.controller('Controller2', function ($scope, $rootScope) {
            $scope.updateTitle = function () {
                $rootScope.title = $scope.sharedVariable;
            };
        });
    </script>
</body>
  
</html>


Output:

Example1

Using $rootScope with Service

In this approach, the $rootScope service is used in a custom service (rootScopeItemService) to perform the sharing of a variable across controllers. The custom service wraps methods for managing an array of items stored in $rootScope.rootScopeItems. The ‘myController‘ controller interacts with this service, enabling users to add, remove, and clear items. This approach enhances code organization by wrapping the shared variable within a service.

Example: Below is an example demonstrating the use of $rootScope with Service in AngularJS to store variables.

HTML




<!DOCTYPE html>
<html lang="en" ng-app="myApp">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>
          Angular $rootScope Example -
        Advanced with Service
      </title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            text-align: center;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }
  
        h1 {
            color: #4CAF50;
        }
  
        h3 {
            color: #333;
        }
  
        input {
            padding: 8px;
            margin: 10px;
        }
  
        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            margin: 5px;
        }
  
        .highlight {
            transition: background-color 0.5s;
        }
  
        .highlight:hover {
            background-color: #45a049;
        }
  
        .item-list {
            list-style: none;
            padding: 0;
        }
  
        .item {
            background-color: #fff;
            padding: 10px;
            margin: 5px;
            border-radius: 5px;
            display: inline-block;
        }
    </style>
</head>
  
<body ng-controller="myController">
    <h1>GeeksforGeeks</h1>
    <h3>Approach 2: Using Angular $rootScope with Service</h3>
    <input type="text" 
           ng-model="newItem" p
           laceholder="Enter a new item">
    <button ng-click="addItem()" 
            class="highlight">
          Add Item
      </button>
    <button ng-click="clearItems()" 
            class="highlight">
          Clear Items
      </button>
    <ul class="item-list">
        <li ng-repeat="item in rootScopeService.getItems()" 
            class="item">
            {{ item }} 
          <button ng-click="removeItem(item)"
                  class="highlight">
            Remove
          </button>
        </li>
    </ul>
    <script src=
      </script>
    
    <script>
        angular.module('myApp', [])
            .service('rootScopeItemService', function ($rootScope) {
                this.getItems = function () {
                    return $rootScope.rootScopeItems || [];
                };
                this.addItem = function (item) {
                    $rootScope.rootScopeItems =
                      $rootScope.rootScopeItems || [];
                    $rootScope.rootScopeItems.push(item);
                };
                this.removeItem = function (item) {
                    const index = 
                          $rootScope.rootScopeItems.indexOf(item);
                    if (index !== -1) {
                        $rootScope.rootScopeItems.splice(index, 1);
                    }
                };
                this.clearItems = function () {
                    $rootScope.rootScopeItems = [];
                };
            })
            .controller('myController', 
                        function ($scope, rootScopeItemService) {
                $scope.addItem = function () {
                    rootScopeItemService.addItem($scope.newItem);
                    $scope.newItem = '';
                };
                $scope.removeItem = function (item) {
                    rootScopeItemService.removeItem(item);
                };
                $scope.clearItems = function () {
                    rootScopeItemService.clearItems();
                };
                $scope.rootScopeService = rootScopeItemService;
            });
    </script>
</body>
  
</html>


Output:

Example2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads