Here , 作者提到
the $scope object used by the two controllers are not the same $scope object
同样的片段:
现在考虑对上面的代码做一点修改。
<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>
对应于 controller2 的 View 已被移动到 controller1 的 View 中。
对于controller2里面的这段代码,
$scope.newTemp = $scope.temp;
Are $scope highlighted above one and the same object?
If yes, how does AngularJS know this?
如果它们相同,controller2 中的 $scope.temp
将是未定义的,那么 $scope.newTemp
会是未定义的吗?
对我而言,考虑到上述程序的o/p,它们并不相同。见下文:
AngularJS 如何从 controller2 中的 controller1 访问 $scope.temp
的值?
请说清楚?
最后,
最佳答案
虽然两个 Controller 中使用的$scope
确实不一样,但它们可以继承彼此的属性。 Angular 的 $scope
就像一棵树,树干是 $rootScope
并且所有其他 $scope
分支都是那个或另一个 $ scope
,因此由于您的 myController2
是 myController1
的子级,您可以访问其中的变量。
$rootScope -> myController1 -> myController2
myController2
可以访问所有父 $scope
,myController1
可以访问 $rootScope
和$rootScope
只能访问自己。
关于javascript - AngularJS 如何在 2 个或更多 Controller 中解析对 $scope 变量的调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308917/