2

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);
        }
      });
    }]);
1
  • sure it can be injected, it will not be same as $scope though, $scope will still be a child of root Commented Jul 14, 2014 at 13:10

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If you intend to use the rootScope so badly, it has a provider just as scope does. Including '$rootScope' into your controller as you do with the '$scope' does the trick.

There's also the $parent attribute of the $scope which could come in handy, but IMO it tends to make code less maintainable if abused. In particular when multiple scopes are nested, as you need to traverse the whole hierarchy.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.