AngularJS Scope
The $scope object is the glue that connects an AngularJS controller to the view, exposing data and functions the HTML can bind to.
What Is $scope?
$scope is an object that AngularJS creates and passes into your controller function. Properties you attach to $scope become available for binding inside the HTML element controlled by that same ng-controller.
Basic $scope Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.name = "John";
});
</script>
</body>
</html>Binding $scope in HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{ name }}</h1>
<input ng-model="name">
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.name = "John";
});
</script>
</body>
</html>In the example above, $scope.name is set inside the controller, displayed with an expression, and also bound two-way to an input using ng-model. Typing in the input immediately updates the heading, because both are reading and writing the same $scope property.
Scope and the View
- $scope is the application object available to both the controller and the view.
- The view (HTML) can only read and write properties that exist on the scope it belongs to.
- $scope acts as glue: the controller sets up data, and the view renders and updates it live.
Root Scope
Every AngularJS application has exactly one root scope, $rootScope, created on the element with ng-app. Every controller's $scope is a child of $rootScope, and any controller inherits properties defined on $rootScope unless it defines its own property of the same name.
Using $rootScope
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.run(function($rootScope) {
$rootScope.companyName = "MyCompany";
});
</script>
</body>
</html>