【问题标题】:How to share $scope between controllers with AngularJs can we access to one controller’s $scope from another controller? [duplicate]如何使用 AngularJs 在控制器之间共享 $scope 我们可以从另一个控制器访问一个控制器的 $scope 吗? [复制]
【发布时间】:2018-09-21 09:22:40
【问题描述】:

我们可以从另一个控制器访问一个控制器的 $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>

我没有在父控制器中获得子范围。我会做什么。写任何服务或其他东西。谢谢

【问题讨论】:

  • 欢迎来到stackoverflow。在控制器之间共享数据是一个非常常见的问题,而正确的答案通常是使用服务(编写一个服务来保存要在控制器之间共享的数据)。
  • 您可以从一个子节点访问父子节点,但不能反过来。创建一个服务来在控制器和模块之间共享数据(比 rootscope 更好)
  • 很多人告诉我避免使用rootscope并使用服务。我是Angular js的新手。如何在这里创建服务。给我一个代码示例。谢谢
  • 这个问题应该有帮助:stackoverflow.com/questions/21919962/…

标签: javascript angularjs ng-controller ng-app


【解决方案1】:

简单的$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 dispatchers

【讨论】:

  • 如何使用服务访问不同的控制器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 2018-06-15
  • 2015-05-03
相关资源
最近更新 更多