这是一个简单的示例,演示一个段落(p)的内容随着输入框(input[type="text"])内容的改变而变。输入框中的内容可能因两个因素改变:
- 用户输入
- 服务器数据更新
示例的原理就是监听输入框的内容,如果输入框内容发生改变,那么对应更新段落对应的内容。
使用jQuery来实现
监听输入框的内容以及改变对应段落的内容之前,需要先获取他们的DOM引用,所以在HTML设定ID或者Class作为钩子。将HTML结构设定为:
<div>
<input id="customGreetingText" type="text" />
<p>
<span id="greetingText">Hello</span>, World!
</p>
<button id="updateGreetingText">Update</button>
</div>
...
<script src="../jquery.js"></script>
上述代码中,定义了一个id为customGreetingText的input元素、一个id为greetingText的span元素以及id为updateGreetingText的按钮。
按照此前所述原理,需要监听input内容的改变。那么在使用jQuery的脚本里,就需要为input的change和keyup事件注册回调函数,当用户输入keyup或者服务器数据更新时change事件发生,更新对应段落的代码:
(function () {
var customGreetingText = $("#customGreetingText");
// Register a change listener on the input field
customGreetingText
.on("change", updateGreetingText)
.on("keyup", updateGreetingText);
// Mock the scenario that content changed by data from server.
$("#updateGreetingText").on("click", function () {
setTimeout(function () {
customGreetingText.val("Hi").trigger("change");
}, 1000);
});
function updateGreetingText() {
$("#greetingText").html(this.value);
}
}());
上述代码中,通过点击按钮button#updateGreetingText使用setTimeout来模拟从服务器获取数据更新的操作。
使用AngularJS来实现
与jQuery不同的是,在使用AngularJS时,不需要为元素定义ID或Class钩子。HTML代码变的更为简洁:
<div>
<input id="customGreetingText" type="text" />
<p>
<span id="greetingText">Hello</span>, World!
</p>
<button id="updateGreetingText">Update</button>
</div>
...
<script src="../jquery.js"></script>
注意到,在HTML结构上有稍许的变化:
- 根元素html有一个
ng-app的属性 - 包含容器div有一个
ng-controller="HelloController"的属性 - 输入框input有一个
ng-model="greeting.text"的属性 - 按钮button由一个
ng-click="update()"的属性
这些属性在AngularJS中称为directive,用于扩展HTML DOM。其中:
ng-app指明AngularJS将在这个元素($rootScope)及其子元素中生效;ng-controller顾名思义,指定View对应的Controller,此例子中为HelloController;ng-model指定input与greeting对象的text属性之间进行双向绑定(即View中的内容发生改变时greeting.text发生改变,反之亦然);- `{{}}`表示
greeting对象的text属性单向绑定到View(即greeting.text发生改变时,View的内容也发生改变,反之无效); - 最后,
ng-click指明当button被点击时,执行了update()回掉函数。
完成HTML结构定义后,定义HelloController:
function HelloController($scope, $timeout) {
$scope.greeting = {
text: "Hello"
};
// Update data from server.
$scope.update = function () {
$timeout(function () {
$scope.greeting.text = "Hi";
}, 1000);
};
}
在DOM Ready之后,Angular将执行HelloController中的内容。
在HelloController中,设定greeting对象为$scope的属性,同时定义了update函数为$scope的方法。$scope是Controller和View之间的粘合剂,Controller给$scope对象设定属性或者方法,View通过$scope获取数据。
可以看到在HelloController构造函数有两个以$开头的参数$scope和$timeout。在AngularJS中,这个称为service($scope和$timeout为内建的service),service用于封装通用的代码,比如$http服务,封装了网络操作相关的代码。
与jQuery明显不同的是,JavaScript代码中没有明确地注册input交互事件的监听函数,这一切都由AngularJS在内部完成,借助于数据绑定,当输入框内容发生变化时,段落的内容也会发生改变。
而这正是AngularJS神奇的开始。