Search code examples
javascriptangularjsrootscope

Accessing $rootScope methods in Controller


In this ng-book JSBin, does $scope.$watch() resolves to $rootScope.$watch() due to prototypal inheritance.

Can we inject $rootScope explicitly inside the controller so that $scope would be same as $rootScope inside the controller, without going through prototypal inheritance?

Replicating code here for reference:

    // open this example and type person.name into the test field
    angular.module('myApp', [])
    .controller('MyController',
    ['$scope', '$parse', function($scope, $parse) {

      $scope.person = {
        name: "Ari Lerner"
      };

      $scope.$watch('expr', function(newVal, oldVal, scope) {
        if (newVal !== oldVal) {
          // Let's set up our parseFun with the expression
          var parseFun = $parse(newVal);
          // Get the value of the parsed expression, set it on the scope for output
          scope.parsedExpr = parseFun(scope);
        }
      });
    }]);

Solution

  • Just inject it the same way as $scope or $parse, anything defined on $rootScope will be then accessible inside your controller.

    app.controller('MyController', ['$scope', '$parse', '$rootScope', 
       function($scope, $parse, $rootScope) {
    
          $rootScope.foo();
    
          console.log($rootScope.bar);
       }
    ]);
    

    etc.