$scope,$injector,$rootScope

Time:2021-9-14

$injector, $rootscope and $scope are important things in the angularjs framework. Clarifying the relationship between them is very useful for our subsequent learning and understanding of the angularjs framework.
1. Obtain the required services from the injector through $injector.get (“servicename”).
2. Scope is the scope in angularjs (actually the place where data is stored), which is very similar to the prototype chain of JavaScript. When looking for angular, give priority to finding your own scope. If it is not found, search upward along the scope chain until it reaches the root scope rootscope.
3, $rootscope is automatically created when angularjs loads modules. Each module will only have one rootscope. After the rootscope is created, it will be added to the $injector as a service. That is, through $injector. Get (“$rootscope”); The root scope of a module can be obtained. More precisely, $rootscope is created by the core module ng of angularjs.

First, introduce angularjs and controller. JS into HTML

controller.js
var app = angular.module('app', []);
var isInjector = angular.injector(['app','ng']);

After loading into chrome, open the console:
$scope,$injector,$rootScope
Enter and the result is true, indicating that $rootscope is contained in the module’s injector in the form of a service.

If you see ng, the code is as follows:

var app = angular.module('app', []);
var isInjector = angular.injector(['app']);  

After loading into chrome, open the console:
$scope,$injector,$rootScope
Description does not depend on ng module, unable to get $rootscope service from injector.

Then change the code to the following:

var app = angular.module('app', []);
var isInjector = angular.injector(['ng']);  

Load into chrome as follows:
$scope,$injector,$rootScope
Get the ng module of the angular core, and the result is true

Z to sum up: $rootscope is indeed created by the core module ng and exists in the injector as a service.

If the ng module is specified when creating the injector, the $rootscope service will be included in the injector; Conversely, if ng is not specified, the $rootscope service is not included.