如何与AngularJs在控制器之间共享$scope,我们可以从另一个控制器访问一个控制器的$scope

How to share $scope between controllers with AngularJs can we access to one controller’s $scope from another controller?

本文关键字:控制器 scope 访问 另一个 一个 我们 AngularJs 之间 共享      更新时间:2023-09-26

我们可以从另一个控制器访问一个控制器的$scope吗?我需要在父、子和孙控制器中获取全部数据,这可能是吗

这是我的脚本

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>

我没有在父控制器中获得子作用域。我该怎么办。写任何服务或什么的。感谢

通过将控制器嵌套到视图中,可以实现简单的$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在控制器之间传递数据,通常使用$broadcast$emit调度器。