我们可以在 AngularJS 中嵌套 Controller 吗?对于嵌套 Controller ,$scope 对象是否在所有 Controller 之间共享。
问题是:-
我可以跨所有 Controller 访问第一个 Controller $scope 值,但无法在第三个 Controller 中获取第二个 Controller 范围对象。您可以在下面的代码片段中运行并检查它。
var app = angular.module("appTest",[]);
function Controller1($scope) {
$scope.text1= "text Sample 1"
}
function Controller2($scope) {
$scope.text2= "text sample 2"
}
function Controller3($scope) {
$scope.text3 = $scope.text1 + " And " + $scope.text2;
}
app.controller("Controller1",Controller1);
app.controller("Controller2",Controller2);
app.controller("Controller3",Controller3);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="appTest">
<div ng-controller="Controller1">
<div>
<h1> First Controller</h1>
First Controller Values is <b> {{text1}}</b>
</div>
<div ng-controller="Controller2">
<h1> Second Controller</h1>
First Controller Values is <b> {{text1}}</b>
<br />
Second controller value is <b> {{text2}}</b>
</div>
<div ng-controller="Controller3">
<h1> Thired Controller</h1>
First Controller Values + Second controller value is <b> {{text3}}</b>
</div>
</div>
</body>
最佳答案
是的,您可以在 angularjs 中嵌套 Controller 。父 Controller 作用域将沿着原型(prototype)链继承,所有子 Controller 都可以访问父 Controller 的作用域。
But I can't get the second controller scope objects in third controller.
原因是您的第三个 Controller 独立于第二个 Controller 。您无法直接从另一个独立 Controller 访问 $scope
属性。您可以将第三个 Controller 嵌套在第二个 Controller 中,也可以使用服务来共享数据(后者更好)。
var app = angular.module("appTest",[]);
function Controller1($scope) {
$scope.text1= "text Sample 1"
}
function Controller2($scope) {
$scope.text2= "text sample 2"
$scope.text1="text Sample 1 from controller 2";//this will be printed in controller 2 and if you want to access parent data, use $parent
}
function Controller3($scope) {
$scope.text3 = $scope.text1 + " And " + $scope.text2;
}
app.controller("Controller1",Controller1);
app.controller("Controller2",Controller2);
app.controller("Controller3",Controller3);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="appTest">
<div ng-controller="Controller1">
<div>
<h1> First Controller</h1> First Controller Values is <b> {{text1}}</b> </div>
<div ng-controller="Controller2">
<h1> Second Controller</h1> First Controller Values is <b> {{$parent.text1}}</b>
First Controller's scope objects value in scond controller <b> {{text1}}</b>
<br /> Second controller value is <b> {{text2}}</b>
<div ng-controller="Controller3">
<h1> Thired Controller</h1> First Controller Values + Second controller value is <b> {{text3}}</b> </div>
</div>
</div>
</body>
关于javascript - 在 AngularJS 中使用嵌套 Controller 时,$scope 对象是否在所有 Controller 之间共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45978615/