A major component of Angular architecture is the $scope
object, which
encapsulates data and communicates between different components of the
application. For this checkpoint it's important to understand several things
about scopes:
-
A $scope object is created automatically for each Angular controller and can be accessed within the controller by declaring
$scope
as one of the controller's dependencies. -
The $scope allows for your controller to provide data and functionality to the view.
-
Changes to $scope variables automatically propagate to the view. That is, the changes are updated simultaneously with the view because data is shared between the controller and the view with data-binding.
-
Scopes can be nested in two different ways: with child scopes or isolate scopes. Child scopes inherit from parent scopes while isolate scopes do not inherit from any other scope.
-
Angular applications also have a single
$rootScope
object which is the parent scope for all other scopes in the application.
Let's take a look at an example of how we attach a variable to $scope
that can be referenced in the view:
In a controller
module = angular.module('ModuleName');
// pass the $scope object into our dependencies so that we can use it in our controller
module.controller('ControllerName', ['$scope', function($scope) {
// attach a property to the object that we'll be using to hold our data that we want to access in the view
$scope.title = 'Our new Angular app';
}]);
In a view
<div class="container" ng-controller="ControllerName">
<h2>{{title}}</h2>
</div>
This will produce an <h2>
with the contents 'Our new Angular app' that will change if we update $scope.title
to something else.
Note that our
$scope
properties must be nested in an element with anng-controller
attribute in order for the data to be accessed properly. Because our scope variable is nested under the element with the controller attribute, the$scope
object is implicit in all of our variables and functions that we use in our view. There is no need to precede the variable with$scope
, as we do in our controller.
The {{}}
double curly braces bind our variable to the contents of our view.