9

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?

2 Answers 2

18

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>
Sign up to request clarification or add additional context in comments.

1 Comment

That is so simple and easy! I find this method better than $emit and $on. Thanks heaps @IvanZh
13

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.

4 Comments

Thanks Minko. I looked at the demo. Should the {{ answer}} in the parent controller should show demo if its binded with the a {{ answer }} in the child controller?
Actually there is a mistake. It should be fixed now.
Just one small question. does the evnt in $scope.$on('response', function (evnt, data) has to be event or it doesnt matter and it can hold any string. (sorry if this sounds silly)
@Neel, it doesn't matter and you can use any string, sometime we use 'e'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.