$scope vs. $rootScope in AngularJs

$scope vs $rootScope in AngularJs

The angular $scope is a JavaScript object which provide the connectivity between the controller and the view. All the model data bind on view (DOM element) using the $scope for a controller.

The angularjs $rootScope is the scope and one application can have only one $rootScope and It use like global variable and access in across application. The angular $rootScope is parent scope and $scopes are child scopes.

The $rootScope objects updates under a specific controller $scope not for all global controllers.

The angular $scope can't be used outside the controller and its only for current controller but the $rootScope can be used anywhere and Its available globally in the application.
All app has one-and-only $rootScope and its lifecycle is the same as the app and its all controllers can have.

The $apply and $watch are scope methods. You can see the working life-cycle in below image.

The Example in detail over $scope vs. $rootScope as given below.

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>$rootScope vs $scope in AngularJs</title>
  <link rel="stylesheet" href="style.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    var app = angular.module('myApp', []);

    //This is Ctrl1.
    app.controller('Ctrl1', ["$scope", "$rootScope", function($scope, $rootScope) {
      $scope.scopeMsg = 'This is $scope.';
      $rootScope.rootScopeMsg = 'This is $rootScope.';

    //This is Ctrl2.
    app.controller('Ctrl2', ["$scope", "$rootScope", function($scope, $rootScope) {
      $scope.scopeMsg = $rootScope.rootScopeMsg;

<body ng-app="myApp">
  <h1>$rootScope vs $scope in AngularJs</h1>
  <div class="border" ng-controller="Ctrl1">
    <div>Result of Ctrl1 $scope : {{scopeMsg}}</div>
    <div>Result of Ctrl1 $rootScope : {{rootScopeMsg}}</div>
  <br />
  <div class="border" ng-controller="Ctrl2">
    <div>Result of Ctrl2 $scope : {{scopeMsg}}</div>


Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

$scope vs $rootScope in AngularJs $scope vs $rootScope in AngularJs Reviewed by Anil Singh on 5:25 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.