What is scope and rootScope?

Technology CommunityCategory: AngularJSWhat is scope and rootScope?
VietMX Staff asked 3 years ago

$scope – A $scope is a JavaScript object which is used for communication between controller and view. Basically, $scope binds a view (DOM element) to the model and functions defined in a controller.

$rootScope – The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope. For example, suppose you have two controllers: Ctrl1 and Ctrl2 as given below:

<!doctype html>
<html>
  <body ng-app="myApp">
    <div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px"> Hello {{msg}}!
      <br />
      Hello {{name}}! (rootScope) 
    </div>
    <br />
    <div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
      Hello {{msg}}! <br />
      Hey {{myName}}! <br />
      Hi {{name}}! (rootScope) 
    </div>
    <script src="lib/angular.js"></script>
    <script>
      var app = angular.module('myApp', []); app.controller('Ctrl1', function ($scope, $rootScope) {
                  $scope.msg = 'World';
                  $rootScope.name = 'AngularJS';
              });
      app.controller('Ctrl2', function ($scope, $rootScope) { $scope.msg = 'Dot Net Tricks';
      $scope.myName = $rootScope.name;
      });
          
    </script>
  </body>
</html>