javascript - 如何使用 AngularJs 在 Controller 之间共享 $scope 我们可以从另一个 Controller 访问一个 Controller 的 $scope 吗?

标签 javascript angularjs ng-controller ng-app

我们可以从另一个 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/

相关文章:

Javascript - 随机图像错误

angularjs - 在 NodeJS 中使用 Express 运行后端和前端服务器是一个好习惯吗?

node.js - MEAN 应用程序中项目的单独页面

javascript - 如何避免重复http请求angularJS

javascript - AngularJs - 将 ng-controller 与 ng-include 一起使用

javascript - 如何过滤显示的数组并重新显示过滤后的列表?

javascript - Threejs TubeGeometry : Applying custom curve causes unexpected twisting

javascript - 去掉TR下所有的onclick

javascript - 如何将对象放入另一个对象 Angular/Javascript

javascript - AngularJS - 参数 'MenuCtrl' 不是函数,未定义