$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>
<html>

<head>
  <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>
  <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;
    }]);
  </script>
</head>

<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>
  </div>
  <br />
  <div class="border" ng-controller="Ctrl2">
    <div>Result of Ctrl2 $scope : {{scopeMsg}}</div>
  </div>
</body>

</html>

The Live Result,

ANIL SINGH

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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.