How to access Child Controller Scope in Parent Controller in Angular?

29,209

Solution 1

You can also use scope prototypal inheritance.

In AngularJS, a child scope normally prototypically inherits from its parent scope. But the answer is a primitive (not object type). So we should put our text data to object, to ensure that prototypal inheritance is in play.
(More info here: https://github.com/angular/angular.js/wiki/Understanding-Scopes)

Controllers:

function MainCtrl($scope) {
  $scope.question = 'question';
  $scope.answer = {};
}
function ChildCtrl($scope) {
  $scope.answer.text = 'demo'; 
}

View:

<div ng-controller="MainCtrl">
  <p>Good {{question}}</p>
  <div ng-controller="ChildCtrl">
    <p>Good {{answer.text}}!</p>
  </div>
  Bind the Child Controller's scope and show here: {{ answer.text}}
<div>

Solution 2

Use the publish/subscribe pattern:

function MainCtrl($scope) {
  $scope.question = 'question'
  $scope.$on('response', function (evnt, data) {
    $scope.answer = data;
  });
}

function ChildCtrl($scope) {
  $scope.$emit('response', 'demo');
}

Demo here.

Share:
29,209
Neel
Author by

Neel

Previously know as @blackops_programmer. I know, it was a pretty lame Display name.

Updated on July 09, 2022

Comments

  • Neel
    Neel almost 2 years

    I am learning Angular JS and I have something like this with a parent controller and child controller:

    <div ng-controller="MainCtrl">
        <p>Good {{question}}</p>
    
        <div ng-controller="ChildCtrl">
            <p>Good {{answer}}!</p>
        </div>
    
        Bind the Child Controller's scope and show here: {{ answer}}
    <div>
    

    Here the child controller is using the scope like this:

    $scope.answer = response.answer;
    

    How do I show the {{ answer }} outside the child controller and inside the parent controller?