Here, the author mentions
the $scope object used by the two controllers are not the same $scope object
Snippet for the same:
Now consider a little modification to the above code.
<body ng-app="myapp">
<div ng-controller="myController1">
<div>{{data.theVar}}</div>
<div>{{data.common}}</div>
<div ng-controller="myController2">
<div>{{data.theVar}}</div>
<div>{{data.common}}</div>
<div>{{temp}}</div>
<div>{{newTemp}}</div>
</div>
</div>
<script>
var module = angular.module("myapp", []);
var myController1 = module.controller("myController1", function($scope) {
$scope.data = {
theVar : "Value One",
common : "common Value"
};
$scope.temp = "John Wick 2 is going to be released soon";
});
var myController2 = module.controller("myController2", function($scope) {
$scope.data = {
theVar : "Value Two"
};
$scope.newTemp = $scope.temp;
console.log("");
});
</script>
</body>
The view corresponding to controller2 has been moved inside the view for controller1.
For this piece of code inside the controller2,
$scope.newTemp = $scope.temp;
Are $scope highlighted above one and the same object?
If yes, how does AngularJS know this?
Had they been same, $scope.temp
in controller2 would be undefined and so then $scope.newTemp
?
For me, they are not the same, considering the o/p of the above program. See below:
But then, I am perplexed as to why they both comes out to be one & the same when I debug,
How does AngularJS able to access value of $scope.temp
from controller1 in controller2?
Please clarify?
Lastly,
Altough it's true that the $scope
used in two controllers are not the same, they can inherit eachother's properties. Angular's $scope
s are like a tree, the trunk is the $rootScope
and every other $scope
branches from that or another $scope
, so since your myController2
is a child of myController1
you can access the variables in it.
$rootScope -> myController1 -> myController2
The myController2
can access all the parent $scope
s, the myController1
can access $rootScope
and the $rootScope
can only access itself.
For your last part, as both controllers have property by name data
, angular will look into current scope first and then hierarchically move up i.e. parent's scope. Therefore, angular founds data
in second controller's scope itself and hence need not refer parent's scope data
variable. But there is no common
key inside that property and hence does not output anything out.
Do look into controller as
syntax of angular, it is meant to keep these conflicts at bay.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With