Managing $scope inheritance

Scopes in AngularJS are bound to the same rules of prototypical inheritance as plain old JavaScript objects. When wielded properly, they can be used very effectively in your application, but there are some "gotchas" to be aware of that can be avoided by adhering to best practices.

Getting ready

Suppose that your application contained the following:

(app.js)

angular.module('myApp', [])
.controller('Ctrl', function() {})

(index.html)

<div ng-app="myApp">
  <div ng-controller="Ctrl" ng-init="data=123">
    <input ng-model="data" />
    <div ng-controller="Ctrl">
      <input ng-model="data" />
    </div>
    <div ng-controller="Ctrl">
      <input ng-model="data" />
    </div>
  </div>
</div>

How to do it…

In the current setup, the $scope instances in the nested ...

Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.