jab*_*128 1 angularjs angularjs-scope
$ scope是AngularJS中的服务还是$ rootScope的实例?
var $injector = angular.element(document).injector();
$injector.get('$rootScope'); //it will return $rootScope
$injector.get('$scope'); //it will return undefined
Run Code Online (Sandbox Code Playgroud)
所以我怀疑$ scope不是'真正的'服务.
gka*_*pak 12
$scope既不是服务也不是实例$rootScope.它是Scope(Angular代码中的私有构造函数)的实例.实际上,$rootScope服务的提供者返回一个实例Scope.
让我们从头开始:
Angular有一个私有(如不能直接从外部访问,例如由你)构造函数,称为Scope.
ScopeAngular可以使用它来创建新的范围对象.(实际上,所有范围,包括隔离范围和rootScope本身,都是使用内部创建的new Scope().)
每个作用域对象都有一个$new()方法,该方法创建一个新的作用域对象,该对象原型继承自其$new()方法被调用的作用域.
加载Angular后,它"需要" $rootScope服务,这将创建rootScope:一个普通的旧Scope对象(没有父作用域).由于服务是Angular中的单例,$rootScope因此只要注入服务,就会提供相同的rootScope对象.
每当需要新的作用域时(例如,对于定义新作用域(正常或隔离)的指令,对于控制器等),将使用$new()已存在的Scope对象的上述方法创建并返回新的Scope对象(即rootScope或rootScope的后代).
那么,$scope注入控制器的依赖是什么?
它是一个Scope对象,由Angular调用封闭范围的$new()方法创建并传递给控制器构造函数.(因此,它不是服务,而是Angular为我们创建的Scope实例.)
也就是说,您的代码可以像这样更改:
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)
Run Code Online (Sandbox Code Playgroud)