Skip to content

Instantly share code, notes, and snippets.

@joelip
Created June 2, 2014 20:36
Show Gist options
  • Save joelip/451c405ddf1fa78cf5c2 to your computer and use it in GitHub Desktop.
Save joelip/451c405ddf1fa78cf5c2 to your computer and use it in GitHub Desktop.

Background: Angular $scope

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:

  1. 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.

  2. The $scope allows for your controller to provide data and functionality to the view.

  3. 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.

  4. 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.

  5. Angular applications also have a single $rootScope object which is the parent scope for all other scopes in the application.

A quick $scope example

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 an ng-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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment