我们可以从另一个 Controller 访问一个 Controller 的 $scope 吗? 我需要获取父、子、孙 Controller 中的全部数据是否可能
这是我的脚本
var app = angular.module('myApp', []);
app.controller('ParentController',ParentController);
function ParentController($scope)
{
$scope.parentName="Parent"
}
app.controller('ChildController1',ChildController1);
function ChildController1($scope)
{
$scope.childName1="Child1"
}
app.controller('ChildController2',ChildController2)
function ChildController2($scope)
{
$scope.childName2="Child2"
}
app.controller('GrandChildController1',GrandChildController1);
function GrandChildController1($scope)
{
$scope.grandChildName1="GrandChild1"
}
这是我的查看代码
<div> ng-app="myApp">
<div ng-controller="ParentController">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
<div ng-controller="ChildController1">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
<div ng-controller="GrandChildController1">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
</div>
</div>
<div ng-controller="ChildController2">
Parent:{{parentName}}
Child1:{{childName1}}
Child2:{{childName2}}
GrandChild1:{{grandChildName1}}
</div>
</div>
</div>
我没有在父 Controller 中获得子范围。我该怎么办。写任何服务或其他东西。谢谢
最佳答案
通过将 Controller 嵌套到 View 中可以实现简单的$scope
继承
<div ng-controller="a">
{{num}}
<div ng-controller="b">
{{num}}
</div>
</div>
app.controller('a', a);
function a($scope) {
$scope.num = 1
}
app.controller('b', b);
function b($scope) {
//$scope.num is inherited by the parent controller
}
您可以随时使用$rootScope在 Controller 之间传递数据,通常使用 $broadcast
和 $emit
dispatchers .
关于javascript - 如何使用 AngularJs 在 Controller 之间共享 $scope 我们可以从另一个 Controller 访问一个 Controller 的 $scope 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34674964/