Scope

Scope is the glue that bind the HTML view with the JavaScript controller. It is an object with properties and methods and is available to both the view and the controller. The scope object ($scope) is passed as an argument in the controller function so that when changes in the view is made, the model and the controller will be updated.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myText = "Hello, World!";
$scope.changeText = function() {
$scope.myText = "Goodbye, World!";
}
});
</script> <p>Click text to see it change!</p>
<div ng-app="myApp" ng-controller="myCtrl">
  <h1 ng-click="changeText()">{{myText}}</h1>
</div>

Scope Demo

Properties in the controller can be reference in the view. If you add properties to the $scope object in the controller, the HTML view gain access to those properties.  In the view, you reference the propertyname (e.g., {{firstName}} instead of using the prefix ($scope).

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "Cornelius";
});
</script>
It is important to know which scope you are working with. For example, if you are working in a large application, there may be sections in the HTML DOM which can only access certain scopes.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.familyMembers = ["Cornelius","Shiela","Joshua","Josiah"];
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<ol>
<li ng-repeat="x in familyMembers">{{x}}</li>
</ol>
</div>
Scope Demo 2

NOTE: The variable x has a different value for each iteration which means that each has its own scope.

All applications have a $rootScope that is created on the HTML element with the ng-app directive that is available to the entire application. If a variable has the same name in BOTH the current scope and the rootScope, the application will use the current scope.  In the example below, the variable color exists in both the controller’s scope and the rootScope. However, it does not overwrite the rootScope color value.

<body ng-app="myApp">
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
$scope.color = "red";
});
</script> <p>The rootScope's favorite color: {{color}}</p>
<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color: {{color}}</p>
</div>
<p>The rootScope's favorite color is still: {{color}}</p>
</body>

Scope Demo 3