Is $scope a service or an instance of $rootScope in AngularJS ?

var $injector = angular.element(document).injector();
$injector.get('$rootScope'); //it will return $rootScope  
$injector.get('$scope');  //it will return undefined  

So I doubt the $scope is not a 'real' service.

有帮助吗?

解决方案

$scope is neither a service nor an instance of $rootScope. It is an instance of Scope (which is a private constructor in Angular's code). In fact, the $rootScope service's provider returns an instance of Scope.

Let's start from the beginning:

  1. Angular has a private (as in not directly accessible from outside, e.g. by you) constructor, called Scope.

  2. Scope can be used by Angular to create new scope objects. (Indeed, all scopes, including isolate scopes and the rootScope itself, are internally created using new Scope().)

  3. Every scope object has a $new() method, which creates a new scope object that prototypically inherits from the scope whose $new() method was called.

  4. As soon as Angular is loaded, it "requires" the $rootScope service, which creates the rootScope: a plain old Scope object (without a parent scope). Since services are singletons in Angular, anytime the $rootScope service is injected, that same rootScope object is provided.

  5. Whenever a new scope is required (e.g. for a directive that defines a new scope (either normal or isolate), for a controller etc.), a new Scope object is created and returned using the aforementioned $new() method of an already existing Scope object (i.e. the rootScope or a descendant of the rootScope).

  6. So, what is the $scope dependency injected into the controllers ?
    It is a Scope object, created by Angular's calling the enclosing scope's $new() method and passed to the controller constructor. (So, it is not a service, but a Scope instance created for us by Angular.)


That said, your code could be changed like this:

var $injector = angular.element(document).injector();
$injector.get('$rootScope');         // it will return $rootScope  
$injector.get('$rootScope').$new();  // it will return a new scope
                                     // (prototypically inheriting from $rootScope)
// Or, if you have access to some other scope
// (example to the controller's $scope)
$scope.$new();  // it will return a new scope
                // (prototypically inheriting from $scope)

其他提示

There is only one true scope in Angular and that is $rootScope. Every other scope inherits from it. $scope is Angular's mechanism to create a model in an mvvm world.

$scope inherit from $rootScope (prototype) but they are define always in context of the views. Number of directives create a new scope (ng-include, ng-if and others), infact ng-controller too creates a new scope that is then linked to the view. The important thing here is that scope does not have a independent existence, and are always referenced in connection of views.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top