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?
In a nutshell: You cannot access child scopes from a parent scope. Your solutions: Define properties in parents and access them from children (read the link above) Use a service to share state.
Angular scopes include a variable called $parent (i.e. $scope. $parent ) that refer to the parent scope of a controller. If a controller is at the root of the application, the parent would be the root scope ( $rootScope ). Child controllers can therefore modify the parent scope since they access to it.
You can still access the parent scope using $parent , but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the = , @ , and & notation.
$scope.$parent refers to the $scope of the parent element. E.g. if you have an element with a controller nested within another element with it's own controller: <div ng-controller="parentController"> ...
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With