python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
$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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions