4

can we access to one controller’s $scope from another controller? I need to get the entire data in parent,child and grandchild controller is it possible

Here is my script

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"
}

Here is my view code

<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>

I didn't get the child scope in parent controller.Wht will i do.Write any service or something.Thank you

Symon Kt
  • 69
  • 2
  • 4
  • Welcome to stackoverflow. Sharing data between controllers is a very frequent question, and the right answer usually is to use a service (write a service to hold the data you want to share between controllers). – Paulo Scardine Jan 08 '16 at 10:41
  • you can get access to the parent child from a child but not the inverse. create a service to share data between controller and module ( better than rootscope ) – AlainIb Jan 08 '16 at 10:41
  • So many peoples told me avoid rootscope and use service.I am new in Angular js.How to create a service here.Give me a code sample.Thank you – Symon Kt Jan 08 '16 at 10:47
  • this question should help: http://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers – sch Jan 08 '16 at 11:00

1 Answers1

0

Simple $scope inheritance is possible by nesting controllers into your view

<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
}

You may always use $rootScope to pass data between the controllers as well, usually using $broadcast and $emit dispatchers.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
vorillaz
  • 6,098
  • 2
  • 30
  • 46