Reputation: 12526
The documentation for Controller
says:
The controller instance can be published into a scope property by specifying ng-controller="as propertyName".
What is the scope
that controller instance is published into? Where does that scope come from? Where can I learn more about this "scope"?
EDIT:
Part of my question is, if you don't use controller as, and instead inject $scope...and then set up your properties on $scope...how does it get from there to the scope that's in the view? Essentially the controller instance right?
Upvotes: 1
Views: 332
Reputation: 49590
ng-controller
creates a child scope whether you use controllerAs
or not. A child scope prototypically inherits from its parent.
<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>
The FooCtrl
instance will get the child scope that was created by the ng-controller
directive:
.controller("FooCtrl", function($scope){
console.log($scope.$id); // 2
});
controllerAs
doesn't do anything about the scope instance that ng-controller
creates. All it does is it simply assigns the controller instance on the scope of the controller (the child scope created by ng-controller
) under the as alias
property
<div ng-controller="FooCtrl as ctrl">
{{ctrl.p1.v}}
</div>
that the controller function assigns onto the instance:
.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
});
Upvotes: 2