What is $scope in AngularJS, and how does scope inheritance work?

AngularJS Data Binding Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

$scope is the object that glues a controller to its view — properties on it are available in the template and are watched for changes. Child scopes (from ng-controller, ng-repeat, directives) inherit prototypally from their parent, which causes the classic “primitive shadowing” bug — hence the “always use a dot” rule (ng-model="user.name", not ng-model="name").

$scope is the bridge between a controller and its template — anything you put on it is available in the view and Angular watches it. The tricky part is scope inheritance: an ng-repeat or nested controller gets a child scope that prototypally inherits from the parent. If you bind ng-model to a primitive that lives on the parent, editing it in the child creates a new property on the child scope and the parent never sees the change. That's why the rule is always bind to an object property — user.name — because then you're writing through a shared reference. controllerAs largely avoids the whole problem.

  • Reading an inherited primitive works; writing to it in a child scope creates a new shadowing property, so the parent doesn't see the change.
  • Binding to an object property (obj.prop) writes through the shared object reference — the parent sees it.
  • controllerAs syntax (ng-controller="HomeCtrl as vm") sidesteps a lot of this by putting state on the controller instance.
  • $rootScope is the top scope — avoid using it as global state.