我是 AngularJS 的新手,我正在通过教程学习它。我对与此相关的概念有些疑问摘要循环由 Angular 提供。
我的应用程序由这两个文件组成:
1) 索引.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 = '';
并且它会自动绑定到特定的视图对象,如 DOM 的本节中所声明的那样index.html
:
<div>
<label>What is your twitter handle?</label>
<input type="text" ng-model="handle" />
</div>
所以任何发生的改变input对象意味着改变handle
财产在$scope反之亦然。
我的理解是,使用 Angular,我不必手动添加经典的普通 JavaScript事件监听器(由添加事件监听器()在我想要观察的对象上)但是 Angular 使用以下方法为我实现了这个功能摘要循环.
然后 Angular(但我不太确定)维护了一个观察者名单 in the 角度上下文。在此列表中,页面中包含的范围内的每个元素(输入、选择等)都有一个观察者对象。
因此观察者包含有关旧值和新价值相关元素的值,如果新值与旧值不同,Angular 会自动更新 DOM 中的相关字段。
据我了解,摘要循环不断迭代观察者名单检查特定观察者的旧值是否与新值不同(如果观察对象的值发生更改)。
那么它到底意味着什么? Angular 不断运行一个循环(类似于while)不断检查某些字段的值是否发生变化?如果发生的话会自动执行特定操作吗?