$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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.