Angular Scope Inheritance Example
by Scott Guymer
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div class="container">
<h1>Angular Inheritance Example</h1>
<p class="well">By default when you nest controllers in angular the inner controllers scope prototypically inherits from the parent controllers scope. This means it gets all of the parent controllers properties and methods</p>
<div class="row">
<div class="col-xs-6">
<h3>Non nested inheritance</h3>
<p>This is what happens when you try to access a parent scope property when it is a simple property on the scope.
<ol>
<li>Change the outer scope</li>
<li>Notice the inner scope updates</li>
<li>Change the inner scope</li>
<li>Notice that the outer scope hasnt changed</li>
</ol>This is because when initially access the parent property to read and display it cant find name on the child scope so it looks to its parent and find it and uses that to display it. However when we try to write to that property it doesnt want to overwrite the property on the parent object and so creates a property with the same name on the child scope and they get out of step.</p>
<div ng-controller="level1">
<label>Outer Scope</label>
<input ng-model="name" />
<div ng-controller="level2">
<label>Inner Scope</label>
<input ng-model="name" />
</div>
</div>
</div>
<div class="col-xs-6">
<h3>Nested Properties</h3>
<p>If we create an object literal on the parent scope and put the property within that things change drastically. Try this
<ol>
<li>Change the outer scope</li>
<li>Notice the inner scope...
JavaScript
var myApp = angular.module('myApp', []);
function level1($scope) {
// basic property
$scope.name = 'Change Me';
// object nested property
$scope.model = {
name: 'Change Me Too'
};
}
function level2($scope) {
// notice this scope is completly empty but we are able to access the properties of the parent.
}