AngularJS 简介
解析 AngularJS 引入方式、核心指令(ng-app/ng-model/ng-bind/ng-init 与 data-ng-*)、双大括号表达式,以及模块与控制器的基础协作结构。
学完这一章,你能够
- 解析 AngularJS 引入方式、核心指令(ng-app/ng-model/ng-bind/ng-init 与 data-ng-*)、双大括号表达式,以及模块与控制器的基础协作结构。
框架引入与脚本放置位置
AngularJS 是一个纯 JavaScript 编写的前端框架,以单个脚本文件形式发布,只需在 HTML 中通过 `<script>` 标签引入(官方历史发行归档位于 GitHub `angular/angular.js/releases`)即可启用。其核心机制是通过指令(`ng-*` 属性)扩展 HTML 语义,并通过表达式将应用数据绑定到页面视图。工程实践中建议将脚本标签置于 `<body>` 底部,使 HTML 结构先完成解析而不被脚本下载阻塞(若需避免未编译插值闪烁,可搭配 `ng-bind` 或 `ng-cloak`)。
核心扩展指令与 HTML5 合法前缀
AngularJS 通过 `ng-` 前缀指令驱动页面:`ng-app` 将某个容器元素(如 `<div>`)声明为应用根节点并在页面加载完成后自动引导框架;`ng-model` 将输入框等表单控件的值同步到应用模型变量(如 `name`);`ng-bind` 则将模型变量绑定到目标元素的文本内容。本站离线 Chromium 实测:向绑定 `ng-model="name"` 的输入框键入 `"Alice"` 后,`<h1>Hello {{name}}</h1>` 变为 `"Hello Alice"`,同页 `<p ng-bind="name">` 同步变为 `"Alice"`;而若移除 `ng-app`,`{{ 5 + 5 }}` 不会被求值,页面直接按字面输出 `"{{ 5 + 5 }}"`。
借助这些声明式能力,AngularJS 简化了单页应用(SPA)的常见交互任务:包括将应用数据自动绑定到 HTML 元素、按集合克隆并重复渲染元素、按条件隐藏或显示节点、在元素背后挂载控制器逻辑,以及提供开箱即用的表单输入验证。
除上述基础指令外,`ng-init` 可在模板上直接初始化应用变量(例如 `ng-init="firstName='John'"`)。对于要求通过严格 HTML5 校验器的文档,由于 HTML5 规范允许以 `data-` 开头的自定义属性,AngularJS 原生支持将所有 `ng-` 指令改写为 `data-ng-` 前缀(如 `data-ng-app`、`data-ng-init`、`data-ng-bind`)。本站离线实测证实:两种前缀均渲染出 `"John"`,且后者可通过原生 `element.dataset.ngApp` 识别为标准 HTML5 `data-*` 属性。
表达式与模块、控制器雏形
AngularJS 表达式写在双大括号 `{{ expression }}` 中,功能与 `ng-bind` 类似,会在书写位置直接输出求值结果。表达式语法接近 JavaScript,支持字面量、运算符与作用域变量,例如 `{{ 5 + 5 }}` 与 `{{ firstName + " " + lastName }}`。本站实测两者在 `ng-app` 容器内分别输出 `"10"` 与 `"John Doe"`。
完整应用通常按模块(Module)与控制器(Controller)分层组织:`angular.module('myApp', [])` 定义应用模块并由 `ng-app="myApp"` 关联到根节点,`app.controller('myCtrl', function($scope) { ... })` 定义控制器并由 `ng-controller="myCtrl"` 挂载作用域数据与行为。本站离线实测:控制器初始化 `$scope.firstName = "John"`、`$scope.lastName = "Doe"` 后页面显示 `"John Doe"`,在输入框中分别改写为 `"Ada"` 与 `"Lovelace"` 后,插值输出即时刷新为 `"Ada Lovelace"`。
脚本放置位置建议
| 提示主题 | 实践说明 |
|---|---|
| 脚本放在 <body> 底部 | 将 AngularJS 与业务脚本放在 <body> 元素底部可减少脚本下载对 HTML 解析渲染的阻塞,加快首屏呈现。 |
缺失 ng-app 指令时的行为
| 提示主题 | 实践说明 |
|---|---|
| 移除 ng-app 不解析表达式 | 未声明 ng-app 时 AngularJS 不会引导编译该区域,浏览器会原样显示 '{{ 5 + 5 }}' 字面文本。 |
HTML5 合法属性前缀提示
| 提示主题 | 实践说明 |
|---|---|
| 使用 data-ng- 通过 HTML5 校验 | HTML5 规范允许以 data- 开头的自定义属性,将 ng- 写作 data-ng- 可在不改变框架行为的前提下满足严格 HTML5 校验。 |
验证 ng-model/ng-bind 同步、缺失 ng-app 对照、data-ng-* 前缀及模块控制器
"""Offline Playwright Chromium lab for AngularJS Ch 02 (intro)."""
import json
from playwright.sync_api import sync_playwright
HTML_PAGE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS Intro Offline Lab</title></head>
<body>
<div id="app1" ng-app="">
<input id="inp1" type="text" ng-model="name">
<h1 id="h1-1">Hello {{name}}</h1>
<p id="bind-1" ng-bind="name"></p>
</div>
<div id="no-app">
<p id="raw-calc">{{ 5 + 5 }}</p>
</div>
<div id="app-init" ng-app="" ng-init="firstName='John'">
<span id="init-ng" ng-bind="firstName"></span>
</div>
<div id="app-data-ng" data-ng-app="" data-ng-init="firstName='John'">
<span id="init-data-ng" data-ng-bind="firstName"></span>
</div>
<div id="app-expr" ng-app="" ng-init="firstName='John';lastName='Doe'">
<p id="expr-sum">{{ 5 + 5 }}</p>
<p id="expr-fullname">{{ firstName + " " + lastName }}</p>
</div>
<div id="app-ctrl" ng-app="myApp" ng-controller="myCtrl">
<input id="ctrl-first" type="text" ng-model="firstName">
<input id="ctrl-last" type="text" ng-model="lastName">
<p id="ctrl-out">{{firstName + " " + lastName}}</p>
</div>
<script>
(function () {
const modules = {};
window.angular = {
module(name, deps) {
if (deps) {
const mod = { _ctrls: {} };
mod.controller = function (cname, fn) {
mod._ctrls[cname] = fn;
return mod;
};
modules[name] = mod;
return mod;
}
return modules[name];
}
};
const app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
function evalExpr(expr, scope) {
const fn = new Function("scope", "with(scope){ return (" + expr + "); }");
const val = fn(scope);
return val === undefined || val === null ? "" : String(val);
}
function execInit(stmt, scope) {
const initProxy = new Proxy(scope, { has: () => true });
const fn = new Function("scope", "with(scope){ " + stmt + "; }");
fn(initProxy);
}
function bootstrapRoot(root) {
const scope = {};
const appName = root.getAttribute("ng-app") ?? root.getAttribute("data-ng-app");
const initCode = root.getAttribute("ng-init") || root.getAttribute("data-ng-init");
if (initCode) execInit(initCode, scope);
const ctrlName = root.getAttribute("ng-controller");
if (appName && ctrlName && modules[appName] && modules[appName]._ctrls[ctrlName]) {
modules[appName]._ctrls[ctrlName](scope);
}
const textBindings = [];
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
let n;
while ((n = walker.nextNode())) {
if (n.nodeValue && n.nodeValue.includes("{{")) {
textBindings.push({ node: n, tpl: n.nodeValue });
}
}
const bindEls = Array.from(root.querySelectorAll("[ng-bind],[data-ng-bind]"));
const modelEls = Array.from(root.querySelectorAll("[ng-model],[data-ng-model]"));
function render() {
for (const b of textBindings) {
b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => evalExpr(ex.trim(), scope));
}
for (const el of bindEls) {
const ex = el.getAttribute("ng-bind") || el.getAttribute("data-ng-bind");
el.textContent = evalExpr(ex, scope);
}
}
for (const el of modelEls) {
const prop = el.getAttribute("ng-model") || el.getAttribute("data-ng-model");
if (scope[prop] !== undefined) el.value = scope[prop];
else scope[prop] = el.value || "";
el.addEventListener("input", () => {
scope[prop] = el.value;
render();
});
}
render();
}
document.querySelectorAll("[ng-app],[data-ng-app]").forEach(bootstrapRoot);
})();
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML_PAGE)
# Case 1: ng-model + {{}} + ng-bind sync
page.fill("#inp1", "Alice")
actual_1 = {
"h1": page.locator("#h1-1").text_content(),
"ng_bind": page.locator("#bind-1").text_content(),
}
expected_1 = {"h1": "Hello Alice", "ng_bind": "Alice"}
cases.append({
"name": "ng_model_and_ng_bind_sync",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: without ng-app vs with ng-app
actual_2 = {
"without_ng_app": page.locator("#raw-calc").text_content(),
"with_ng_app": page.locator("#expr-sum").text_content(),
}
expected_2 = {"without_ng_app": "{{ 5 + 5 }}", "with_ng_app": "10"}
cases.append({
"name": "without_ng_app_literal_expression",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: ng-init vs HTML5 data-ng-* prefix
actual_3 = {
"ng_prefix": page.locator("#init-ng").text_content(),
"data_ng_prefix": page.locator("#init-data-ng").text_content(),
"has_dataset_ng_app": page.evaluate("() => 'ngApp' in document.getElementById('app-data-ng').dataset"),
}
expected_3 = {
"ng_prefix": "John",
"data_ng_prefix": "John",
"has_dataset_ng_app": True,
}
cases.append({
"name": "ng_init_and_data_ng_html5_prefix",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: expressions arithmetic & string concat
actual_4 = {
"sum": page.locator("#expr-sum").text_content(),
"concat": page.locator("#expr-fullname").text_content(),
}
expected_4 = {"sum": "10", "concat": "John Doe"}
cases.append({
"name": "expression_arithmetic_and_concat",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: angular.module + controller + two-way input updates
init_full = page.locator("#ctrl-out").text_content()
page.fill("#ctrl-first", "Ada")
page.fill("#ctrl-last", "Lovelace")
updated_full = page.locator("#ctrl-out").text_content()
actual_5 = {"initial": init_full, "updated": updated_full}
expected_5 = {"initial": "John Doe", "updated": "Ada Lovelace"}
cases.append({
"name": "module_and_controller_two_way",
"expected": expected_5,
"actual": actual_5,
"passed": actual_5 == expected_5,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对输入 Alice 后 {{name}} 与 ng-bind 同步;无 ng-app 保留 '{{ 5 + 5 }}';data-ng-* 渲染 John 且具备 dataset.ngApp;控制器从 John Doe 动态更新为 Ada Lovelace。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:69e5470ef511002e2ff7f2eba066fb3cc9dd5e2b8fc2d921ad49ea3f29cb886a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:50170631bd2c3bf115d94fba75735cc3ad6407e3e4cc21e6d875df7962b92e7d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在需要通过严格 HTML5 校验的页面里常看到 data-ng-app 而非 ng-app?如果完全删掉 ng-app 会发生什么?
展开参考解答
HTML5 标准只允许自定义属性以 data- 开头,AngularJS 在编译阶段会自动归一化 data-ng-* 与 ng-* 前缀,因此二者运行时等价;若移除 ng-app,框架不会引导该 DOM 子树,双大括号表达式会作为普通纯文本直接显示。