ang123
ang123

Reputation: 33

Parent and child scopes in angular

Can anyone please provide me with simple examples to understand parent and child scopes in angular better? I have tried the following but it prints hello {{person}} as output.

<!DOCTYPE html>
<html>
<head>
<title> Simple app </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js">

</script>
</head>
<body>
<h1 ng-app="MyApp3" ng-controller="ParentController">
<h1 ng-controller="ChildController">hello {{person}}</h1>
</h1>
</body>
<script>
var app=angular.module('MyApp3',[]);
app.controller('ParentController',function($scope)
{
    $scope.person =
    {
        name : "Angular"
    };
});
app.controller('ChildController',function($scope)
{
    $scope.person.name="Angular";
    $scope.person.age=40;
});
</script>
</html>

Upvotes: 0

Views: 103

Answers (1)

Todd Palmer
Todd Palmer

Reputation: 1102

I cleaned up your code a bit. Notice the <div> elements to contain the controller scopes.

You can see how the ChildController is accessing the person in the ParentController because the object shows the name "Child" even though it is outside of the ChildController <div>.

var app=angular.module('MyApp3',[]);
app.controller('ParentController',function($scope)
{
    $scope.person =
    {
        name : "Parent"
    };
});
app.controller('ChildController',function($scope)
{
    $scope.person.name="Child";
    $scope.person.age=40;
});
<!DOCTYPE html>
<html>
<head>
<title> Simple app </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js">
</script>
</head>
<body ng-app="MyApp3" ng-controller="ParentController">
<h1>This shows the object</h1>
  <p>{{person}}</p>
  
<div ng-controller="ChildController">  
<h1>This shows the name</h1>
  <p>{{person.name}}</p>
  </div>
</body>
</html>

Upvotes: 1

Related Questions