AngularJS Example: $rootScope vs $scope

In this example a color variable is set on the $rootScope at the beginning, inside the run block. There is only one $rootScope, so this is kind of like setting a global variable. Later inside GroverController a color variable is set on it’s $scope, this overrides the $rootScope inside this controller. View a demo here.

<!DOCTYPE html>
<html ng-app="myApp"> 
<head>
  <title>$rootScope and $scope</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
</head>
<body>
  <p>Big Bird is {{ color }}.</p>
  <div ng-controller="GroverController">
    <p>Grover is {{ color }}.</p>
  </div>
  <div ng-controller="SunController">
    <p>The sun is {{ color }}.</p>
  </div>
  <script type="text/javascript">
    var app = angular.module('myApp', []).run(function($rootScope) {
      $rootScope.color = 'yellow';
    });
    app.controller('GroverController', function($scope) {
      $scope.color = 'blue';
    });
    app.controller('SunController', function($scope) {
    });
  </script>
</body>
</html>
This entry was posted in Uncategorized. Bookmark the permalink.