I am understanding rootScope and how it works.

51 views Asked by At

I am understanding rootScope and how it works. While following a tutorial its been mentioned that a value mentioned on rootScope is available through entire application and if anything changes on rootScope it will reflect everywhere. In my code below

<div ng-app="sample">
  <div ng-controller="emp">
    Hello {{name}}. Your tax amount is ${{taxAmount}}
    <div ng-controller="empDetails">
       Name : {{name}} <br/>
       Salary: {{sal}}<br/>
       Dept: {{dept}} <br/>
       Tax Amount: {{taxAmount}}
    </div>
  </div>

var app = angular.module('sample', [])
         .run( ['$rootScope', function($rootScope){
            $rootScope.taxAmount = 40;
         }]);

app.controller('emp', ['$scope', function($scope){
  $scope.name = "John";
}]);

app.controller('empDetails', ['$scope', '$rootScope', function($scope, $rootScope){
  $scope.sal = 40000;
  $scope.dept= 'CS';
  $rootScope.taxAmount = 50;
}]);

For both controller I can access the value TaxAmount but on empDetails I have changed the value on rootScope. Since explicitly mentioning value on rootScope at controller level is not a good practice why to use rootScope in controller 2. Is there any practical need in real world. Should we use it.

0

There are 0 answers