As a newcomer to AngularJS, I am currently following a tutorial to learn more about it. One concept that has caught my attention is the Digest Loop in Angular.
In my application, there are two main files:
1) index.html:
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<title>Learning AngularJS</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<!-- External CSS and JS files -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script src="//code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">AngularJS</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><i class="fa fa-home"></i> Home</a></li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div ng-controller="mainController">
<div>
<label>Enter your Twitter handle:</label>
<input type="text" ng-model="handle" />
</div>
<hr />
<h1>twitter.com/{{ lowercasehandle() }}</h1>
</div>
</div>
</body>
</html>
2) app.js:
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', '$filter', '$timeout', function($scope, $filter, $timeout) {
// Bound variable for input handling:
$scope.handle = '';
// Function returning lowercase version of handle variable:
$scope.lowercasehandle = function() {
return $filter('lowercase')($scope.handle);
};
// Watch on handle property changes:
$scope.$watch('handle', function(newValue, oldValue) {
console.info('Changed!');
console.log('Old:' + oldValue);
console.log('New:' + newValue);
});
$timeout(function() {
$scope.handle = 'newtwitterhandle';
console.log('Scope changed!');
}, 3000);
}]);
From my understanding, the handle
variable is declared within the Angular scope here:
$scope.handle = '';
This variable is automatically connected to a specific object in the view, as indicated in this section of index.html
:
<div>
<label>What is your twitter handle?</label>
<input type="text" ng-model="handle" />
</div>
With Angular, I don't need to manually add event listeners like traditional JavaScript. Instead, Angular uses the Digest Loop feature to keep track of these changes for me.
It seems that Angular maintains a list of watchers in its context, with each watcher corresponding to elements on the page (such as inputs, selects, etc.). So, whenever the value of an element changes, Angular automatically updates the related field in the DOM if needed.
The digest loop continuously checks this watcher list to monitor any changes in values, updating the DOM accordingly. Essentially, it's like a continuous cycle that ensures data consistency and triggers operations when necessary.