AngularJS Getting started with AngularJS The importance of scope


Example

As Angular uses HTML to extend a web page and plain Javascript to add logic, it makes it easy to create a web page using ng-app, ng-controller and some built-in directives such as ng-if, ng-repeat, etc. With the new controllerAs syntax, newcomers to Angular users can attach functions and data to their controller instead of using $scope.

However, sooner or later, it is important to understand what exactly this $scope thing is. It will keep showing up in examples so it is important to have some understanding.

The good news is that it is a simple yet powerful concept.

When you create the following:

<div ng-app="myApp">
 <h1>Hello {{ name }}</h1>
</div>

Where does name live?

The answer is that Angular creates a $rootScope object. This is simply a regular Javascript object and so name is a property on the $rootScope object:

angular.module("myApp", [])
  .run(function($rootScope) {
    $rootScope.name = "World!";
  });

And just as with global scope in Javascript, it's usually not such a good idea to add items to the global scope or $rootScope.

Of course, most of the time, we create a controller and put our required functionality into that controller. But when we create a controller, Angular does it's magic and creates a $scope object for that controller. This is sometimes referred to as the local scope.

So, creating the following controller:

<div ng-app="myApp">
  <div ng-controller="MyController">
    <h1>Hello {{ name }}</h1>
  </div>
</div>

would allow the local scope to be accessible via the $scope parameter.

angular.module("myApp", [])
  .controller("MyController", function($scope) {
    $scope.name = "Mr Local!";
  });

A controller without a $scope parameter may simply not need it for some reason. But it is important to realize that, even with controllerAs syntax, the local scope exists.

As $scope is a JavaScript object, Angular magically sets it up to prototypically inherit from $rootScope. And as you can imagine, there can be a chain of scopes. For example, you could create a model in a parent controller and attach to it to the parent controller's scope as $scope.model.

Then via the prototype chain, a child controller could access that same model locally with $scope.model.

None of this is initially evident, as it's just Angular doing its magic in the background. But understanding $scope is an important step in getting to know how Angular works.