AngularJS - SPLessons

AngularJS Scopes

Chapter 14

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

AngularJS Scopes

AngularJS Scopes

shape Description

AngularJS Scopes are JavaScript object that primarily refers to the application model. Scopes are organized in a hierarchical structure and are considered as an execution context for expressions.

Root Scope

There is a root scope available in the entire application, which means it is a parent and the root scope multiple child scopes. Own $scope(which is a child of the root scope) is maintained by every view, so if any one view controller is assigned a $scope variable remains invisible to other controllers when all variables are present.

The $scope object connects controller with view to execute the expressions context and model the accessible data to be displayed in the view page. If a variable possess the same name in both the current scope and rootScope, the application uses the one in the current scope.

shape Conceptual
figure

shape Example

<!DOCTYPE html>
<html>

<head>
  <title>AngularJS Scope</title>
</head>

<body ng-app="spApp">
  <h1>AngularJS Scope</h1>
  <div ng-controller="SPController-1">
    {{data.theVar}}
  </div>

  <div ng-controller="SPController-2">
    {{data.theVar}}
  </div>

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
  <script src="App.js"></script>
  <script src="SPController-1.js"></script>
  <script src="SPController-2.js"></script>
</body>

</html>

var module = angular.module("spApp", []);

var spController1 = module.controller("SPController-1", function($scope) {
      $scope.data = { theVar : "View One"};
 });

var spController2 = module.controller("SPController-2", function($scope) {
       $scope.data = { theVar : "View Two"};
 });

In the above example, there are two views. Each view has its own controllers. Every controller sets the variable data.theVar to various values.

  • Root $scope
  • $scope for SPController-1
  • $scope for SPController-2

The $scope object is used by two controllers, but,  $scope object is different for each controller. The two controller functions for the views are assigned various values for the data.theVar variable in each $scope object.

Output:

Summary

shape Key Points

  • Each view has its own $scope.
  • If a variable possess the same name in both the current scope and rootScope, the application uses the one in the current scope.