【发布时间】:2016-02-15 02:09:21
【问题描述】:
我是 AngularJS 的新手,我正在学习它的教程。我对 Angular 提供的 Digest Loop 相关的概念有些怀疑。
我的应用程序由这两个文件组成:
1) index.html:
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<title>Learn and Understand AngularJS</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<style>
html, body, input, select, textarea
{
font-size: 1.05em;
}
</style>
<!-- load angular via CDN -->
<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>What is 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) {
// Variable that is bound to the input into the view handled by the 'mainController' controller:
$scope.handle = '';
// This variable is a function putted into the $scope and contain the lowecase content of the handle variable:
$scope.lowercasehandle = function() {
return $filter('lowercase')($scope.handle);
};
// I explicitly declare a whatche on the handle property: when the value of this propertu change the function() is performed:
$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);
}]);
据我了解,handle 变量是通过以下方式声明到 Angular 范围内的:
$scope.handle = '';
它会自动绑定到特定的视图对象,如index.html DOM 的本节中声明的那样:
<div>
<label>What is your twitter handle?</label>
<input type="text" ng-model="handle" />
</div>
因此,此 input 对象发生的任何更改都意味着 $scope 中 handle 属性的更改,反之亦然。
我的理解是,使用 Angular,我不必手动添加经典的原生 JavaScript EventListener(通过 addEventListener() 在我想要观察的对象上) 但 Angular 使用 Disgest Loop 为我实现了这个功能。
然后Angular(但我不太确定)在Angular Context中维护一个观察者列表。在此列表中,页面中包含的范围内的每个元素(输入、选择等)都有一个观察者对象。
因此,观察者包含有关相关元素的旧值和新值的信息,如果新值与旧值不同,Angular 会自动更新DOM 中的相关字段。
据我了解,摘要循环不断迭代此 观察者列表 以检查特定观察者的旧值是否与新值不同(如果观察对象的值已更改)。
那么它的确切含义是什么? Angular 会持续运行一个循环(类似于 while),不断检查某个字段的值是否发生变化?如果它发生自动执行特定操作?
【问题讨论】:
标签: javascript angularjs dom-events javascript-framework