使用 "Controller as" 语法时,控制器实例 属性 发布到什么 "scope"?
When using "Controller as" syntax, what "scope" is the controller instance property published into?
Controller
的文档说:
The controller instance can be published into a scope property by specifying ng-controller="as propertyName".
控制器实例发布到的 scope
是什么?该范围从何而来?我在哪里可以了解更多关于此 "scope" 的信息?
编辑:
我的部分问题是,如果您不使用控制器,而是注入 $scope...然后在 $scope 上设置您的属性...它如何从那里到达范围在视图中?本质上是控制器实例吧?
ng-controller
无论您是否使用 controllerAs
都会创建一个子作用域。子作用域原型继承自其父作用域。
<div ng-app="app">
{{$id}} - the outer scope id is 1 (same as root here)
<div ng-controller="FooCtrl">
{{$id}} - the child scope id is 2
</div>
</div>
FooCtrl
实例将获得由 ng-controller
指令创建的子范围:
.controller("FooCtrl", function($scope){
console.log($scope.$id); // 2
});
controllerAs
不会对 ng-controller
创建的作用域实例做任何事情。它所做的只是简单地将控制器实例分配给 as alias
属性
下的控制器范围(由 ng-controller
创建的子范围)
<div ng-controller="FooCtrl as ctrl">
{{ctrl.p1.v}}
</div>
控制器函数分配给实例:
.controller("FooCtrl", function($scope){
this.p1 = {v: "p1"};
// the following is true
console.log($scope.ctrl === this);
// but don't do this, since the controller function shouldn't know about ctrl alias
});
Controller
的文档说:
The controller instance can be published into a scope property by specifying ng-controller="as propertyName".
控制器实例发布到的 scope
是什么?该范围从何而来?我在哪里可以了解更多关于此 "scope" 的信息?
编辑:
我的部分问题是,如果您不使用控制器,而是注入 $scope...然后在 $scope 上设置您的属性...它如何从那里到达范围在视图中?本质上是控制器实例吧?
ng-controller
无论您是否使用 controllerAs
都会创建一个子作用域。子作用域原型继承自其父作用域。
<div ng-app="app">
{{$id}} - the outer scope id is 1 (same as root here)
<div ng-controller="FooCtrl">
{{$id}} - the child scope id is 2
</div>
</div>
FooCtrl
实例将获得由 ng-controller
指令创建的子范围:
.controller("FooCtrl", function($scope){
console.log($scope.$id); // 2
});
controllerAs
不会对 ng-controller
创建的作用域实例做任何事情。它所做的只是简单地将控制器实例分配给 as alias
属性
ng-controller
创建的子范围)
<div ng-controller="FooCtrl as ctrl">
{{ctrl.p1.v}}
</div>
控制器函数分配给实例:
.controller("FooCtrl", function($scope){
this.p1 = {v: "p1"};
// the following is true
console.log($scope.ctrl === this);
// but don't do this, since the controller function shouldn't know about ctrl alias
});