How AngularJS manages inheritance in controllers scopes

angularjs2

Understanding $scope inheritance in controllers on AngularJS

When a project grows and you start using nested controllers, you start thinking on how inheritance can give us some advantages, like storing API-retrieved data on a parent controller, and then use it on two sibling controllers.

Given this scenario, there’s a specific behavior that is worth being clarified.

Let’s start with an example:

Say we have a parent controller and a child controller. We declare on the parent:
$scope.name = ‘Prince’

And then we have on the child a new method change name:
$scope.changeName = function(name) {
$scope.name = name;
}

Of course, we then call:
changeName(‘The Artist Formerly Known as Prince’)

The expected behaviour is to change the name attribute of the parent’s scope. Guess what? It isn’t changed. 

What happened?

What we have done is create another variable on the child scope called name. But parent’s name attribute is still ‘Prince’. 

How we fix this behaviour?

Just using objects instead of simple variables.

Applied to the previous example, we would have the following on the parent controller:
$scope.person = {
name: ‘Prince’
}

And on the child controller we would have the following method:
$scope.changeName = function(name) {
$scope.parent.name = name
}

VOILA! Everything acts as expected!

 … but what’s happening behind the curtains?

Child controller first tries to resolve $scope.parent object, it realizes that he doesn’t have it and then asks to its parent, who returns the reference.
Is then, when we really have the object that we want to change, when child controller resolves [previousObjectResolution].name, and overwrites one of its attributes successfully.

Tagged:Etiquetas:

Leave A Comment?