AngularJS 实例
系统梳理 AngularJS 从入门表达式、指令、控制器、过滤器、表格与异步数据,到 DOM 事件、表单校验、工具 API、Bootstrap 集成及笔记/备忘录应用的综合实例索引与实测。
学完这一章,你能够
- 系统梳理 AngularJS 从入门表达式、指令、控制器、过滤器、表格与异步数据,到 DOM 事件、表单校验、工具 API、Bootstrap 集成及笔记/备忘录应用的综合实例索引与实测。
入门交互实例与基础、表达式、指令、控制器分类
本章节汇总 AngularJS 教程各核心主题的典型交互实例,便于按知识点横向复习与动手调试。最具代表性的入门示例在 `ng-app=""` 容器中用 `ng-model="name"` 绑定文本框,并通过 `<h1>Hello {{name}}</h1>` 实时输出问候语:本站离线 Chromium 实测输入 `"BlueSky"` 后标题即时更新为 `"Hello BlueSky"`。
在基础与表达式两类实例中,重点涵盖了首个表达式与指令、兼容 HTML5 校验的 `data-ng-*` 写法、控制器入门,以及不使用 `ng-app` 时原始花括号不被编译的对照;表达式部分系统演示了数字运算、字符串拼接、对象属性访问与数组索引,并分别对比 `{{ }}` 插值与 `ng-bind` 两种绑定方式。本站实测确认:在已引导区域内数值 `5 + 5`、对象全名与数组元素分别求值为 `10|John Doe|30`,而未挂载 `ng-app` 的区块保留字面文本 `{{ 5 + 5 }}`。
指令与控制器两类实例进一步聚焦数据驱动视图:指令部分涵盖 `ng-model` 双向绑定以及 `ng-repeat` 遍历数组与对象集合;控制器部分演示控制器属性、方法定义以及将控制器拆分到独立 JavaScript 文件中的组织方式,帮助理解视图模板与业务逻辑解耦。
过滤器、异步数据、表格与数据库读取分类
过滤器与异步请求实例展示了数据格式化与远端拉取:过滤器部分包含表达式级 `uppercase`、`lowercase`、`currency` 货币格式化,以及指令级 `orderBy` 排序和输入关键词实时过滤;XMLHttpRequest 部分则演示利用 `$http` 读取静态 JSON 文件并将返回数组绑定到视图。
表格与数据库读取实例将上述能力组合成典型列表页:涵盖基础表格展示、自定义 CSS 样式美化、按字段排序、结合 `uppercase` 转换列值、使用 `$index` 生成序号,以及利用 `$even` / `$odd` 实现斑马纹隔行配色;数据库部分说明前端通过 `$http` 请求后端 PHP/ASP.NET 接口间接读取 MySQL 或 SQL Server 并以 JSON 格式呈现。本站 Chromium 实测对 3 条记录按国家升序排列(首行 `AUSTRIA`)、应用隔行背景色 `rgb(241, 241, 241)` 与 `rgb(255, 255, 255)`,输入关键词 `"ger"` 后精确过滤出 `["1", "Alfreds", "GERMANY", "$19.50"]`,同时核验 `lowercase`/`uppercase`/`currency` 输出 `john|JOHN|$12.50`。
DOM、事件、模块、表单、API、Bootstrap 与综合应用分类
DOM 与事件实例聚焦界面状态控制:通过 `ng-disabled`、`ng-show`、`ng-hide` 动态切换按钮可用性与元素显隐,并利用 `ng-click` 响应点击事件;模块实例则对比直接在 `<body>` 内联定义模块与将模块、控制器拆分到外部脚本文件的两种写法。
表单与全局 API 实例覆盖输入校验与类型工具:表单部分演示数据绑定、必填与邮箱格式校验(配合 `$dirty`、`$invalid` 状态);API 部分涵盖 `angular.lowercase()`、`angular.uppercase()`、`angular.isString()` 与 `angular.isNumber()` 等基础工具函数(注:1.7.x 起 `angular.lowercase` 与 `angular.uppercase` 已移除,现代代码应直接使用原生字符串大小写方法)。本站实测确认勾选禁用使按钮变为禁用态、点击切换隐藏面板(点击计数 `1`)、非法邮箱呈现 `dirty:invalid` 而合法邮箱转为 `dirty:valid`,4 项工具函数返回值均符合预期。
Bootstrap 与完整应用实例展示整站级整合方案:Bootstrap 部分结合响应式栅格/表单样式与 `ng-include` 拆分列表和编辑区;应用部分提供“笔记应用”与“备忘录(Todo)应用”两个端到端范例。本站 Chromium 实测备忘录应用完整增删流程:初始 2 条任务(含 1 条已完成),新增 `"复习路由配置"` 后增至 `3` 条,点击删除已勾选后精确保留 `["编写过滤器表格", "复习路由配置"]` 两条待办项。
离线 Chromium 综合实测表达式、过滤器表格、DOM 校验 API 与备忘录 CRUD
展开查看收起
"""Offline Playwright Chromium lab for AngularJS Ch 26: examples (comprehensive interactive showcase)."""
import json
from playwright.sync_api import sync_playwright
EXAMPLES_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS 综合实例离线实验</title>
<style>
.row-even { background-color: rgb(241, 241, 241); }
.row-odd { background-color: rgb(255, 255, 255); }
.ng-hide { display: none !important; }
</style>
</head>
<body>
<!-- 1. Flagship intro ng-model + expression & unbootstrapped comparison -->
<section id="sec-intro" ng-app="">
<input id="name-input" type="text">
<h1 id="hello-out">Hello </h1>
<p id="expr-calc"></p>
</section>
<section id="sec-no-app">
<p id="raw-expr">{{ 5 + 5 }}</p>
</section>
<!-- 2. Filters + sorted zebra table -->
<section id="sec-table">
<input id="filter-input" type="text">
<table id="data-tbl"><tbody></tbody></table>
<p id="filter-summary"></p>
</section>
<!-- 3. DOM, Events, Form validation, Core APIs -->
<section id="sec-dom">
<input id="chk-disable" type="checkbox">
<button id="btn-target">提交</button>
<button id="btn-toggle">切换显示</button>
<div id="toggle-panel">可见面板</div>
<input id="email-input" type="email" required>
<span id="email-state"></span>
</section>
<!-- 4. Todo / Memo app -->
<section id="sec-todo">
<input id="todo-input" type="text">
<button id="todo-add">新增</button>
<button id="todo-remove">删除已勾选</button>
<ul id="todo-list"></ul>
</section>
<script>
// 1. Intro binding & expression evaluation
const nameInput = document.getElementById('name-input');
const helloOut = document.getElementById('hello-out');
nameInput.addEventListener('input', () => {
helloOut.textContent = 'Hello ' + nameInput.value;
});
const person = { first: 'John', last: 'Doe' };
const scores = [10, 20, 30];
document.getElementById('expr-calc').textContent =
(5 + 5) + '|' + (person.first + ' ' + person.last) + '|' + scores[2];
// 2. Filters (uppercase, lowercase, currency, orderBy, filter) + table ($index, $even, $odd)
const records = [
{ Name: 'Alfreds', Country: 'Germany', Price: 19.5 },
{ Name: 'Centro', Country: 'Mexico', Price: 8.2 },
{ Name: 'Ernst', Country: 'Austria', Price: 42.0 }
];
function renderTable(query) {
const q = (query || '').toLowerCase();
const filtered = records
.filter(r => !q || r.Name.toLowerCase().includes(q) || r.Country.toLowerCase().includes(q))
.slice()
.sort((a, b) => a.Country.localeCompare(b.Country));
const tbody = document.querySelector('#data-tbl tbody');
tbody.innerHTML = '';
filtered.forEach((item, idx) => {
const tr = document.createElement('tr');
tr.className = idx % 2 === 0 ? 'row-even' : 'row-odd';
tr.innerHTML =
'<td>' + (idx + 1) + '</td>' +
'<td>' + item.Name + '</td>' +
'<td>' + item.Country.toUpperCase() + '</td>' +
'<td>$' + item.Price.toFixed(2) + '</td>';
tbody.appendChild(tr);
});
}
renderTable('');
document.getElementById('filter-input').addEventListener('input', (e) => renderTable(e.target.value));
document.getElementById('filter-summary').textContent =
'JOHN'.toLowerCase() + '|' + 'john'.toUpperCase() + '|$' + (12.5).toFixed(2);
// 3. DOM (ng-disabled, ng-show/ng-hide), Events (ng-click), Form validation & AngularJS utility APIs
const chkDisable = document.getElementById('chk-disable');
const btnTarget = document.getElementById('btn-target');
chkDisable.addEventListener('change', () => { btnTarget.disabled = chkDisable.checked; });
const btnToggle = document.getElementById('btn-toggle');
const togglePanel = document.getElementById('toggle-panel');
let clicks = 0;
btnToggle.addEventListener('click', () => {
clicks += 1;
togglePanel.classList.toggle('ng-hide');
});
const emailInput = document.getElementById('email-input');
const emailState = document.getElementById('email-state');
let emailDirty = false;
function updateEmailState() {
const valid = emailInput.checkValidity();
emailState.textContent = (emailDirty ? 'dirty' : 'pristine') + ':' + (valid ? 'valid' : 'invalid');
}
emailInput.addEventListener('input', () => { emailDirty = true; updateEmailState(); });
updateEmailState();
window.angularApi = {
lowercase: (s) => (typeof s === 'string' ? s.toLowerCase() : s),
uppercase: (s) => (typeof s === 'string' ? s.toUpperCase() : s),
isString: (v) => typeof v === 'string',
isNumber: (v) => typeof v === 'number',
getClicks: () => clicks
};
// 4. Todo / Memo app (备忘录应用)
let todos = [
{ text: '学习 AngularJS 指令', done: true },
{ text: '编写过滤器表格', done: false }
];
function renderTodos() {
const ul = document.getElementById('todo-list');
ul.innerHTML = '';
todos.forEach((t, i) => {
const li = document.createElement('li');
li.innerHTML = '<input type="checkbox" data-idx="' + i + '"' + (t.done ? ' checked' : '') + '><span>' + t.text + '</span>';
li.querySelector('input').addEventListener('change', (ev) => {
todos[i].done = ev.target.checked;
});
ul.appendChild(li);
});
}
renderTodos();
document.getElementById('todo-add').addEventListener('click', () => {
const val = document.getElementById('todo-input').value.trim();
if (!val) return;
todos.push({ text: val, done: false });
document.getElementById('todo-input').value = '';
renderTodos();
});
document.getElementById('todo-remove').addEventListener('click', () => {
todos = todos.filter(t => !t.done);
renderTodos();
});
</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)
try:
page = browser.new_page()
page.set_content(EXAMPLES_HTML, wait_until="load")
# Case 1: Intro binding + expressions vs unbootstrapped container
page.fill("#name-input", "BlueSky")
res1 = {
"hello_heading": page.locator("#hello-out").inner_text(),
"expr_summary": page.locator("#expr-calc").inner_text(),
"without_ng_app": page.locator("#raw-expr").inner_text(),
}
exp1 = {
"hello_heading": "Hello BlueSky",
"expr_summary": "10|John Doe|30",
"without_ng_app": "{{ 5 + 5 }}",
}
cases.append(dict(
name="intro_binding_and_expressions",
expected=exp1,
actual=res1,
passed=(res1 == exp1),
))
# Case 2: Filters (uppercase/lowercase/currency/orderBy/filter) & zebra table ($index, $even, $odd)
all_rows = page.evaluate("""() => Array.from(document.querySelectorAll('#data-tbl tbody tr')).map(tr => ({
cls: tr.className,
bg: getComputedStyle(tr).backgroundColor,
cells: Array.from(tr.querySelectorAll('td')).map(td => td.textContent)
}))""")
page.fill("#filter-input", "ger")
filtered_rows = page.evaluate("""() => Array.from(document.querySelectorAll('#data-tbl tbody tr')).map(tr =>
Array.from(tr.querySelectorAll('td')).map(td => td.textContent)
)""")
res2 = {
"sorted_first_row_country": all_rows[0]["cells"][2],
"zebra_classes": [r["cls"] for r in all_rows],
"even_bg": all_rows[0]["bg"],
"odd_bg": all_rows[1]["bg"],
"filtered_rows": filtered_rows,
"filter_summary": page.locator("#filter-summary").inner_text(),
}
exp2 = {
"sorted_first_row_country": "AUSTRIA",
"zebra_classes": ["row-even", "row-odd", "row-even"],
"even_bg": "rgb(241, 241, 241)",
"odd_bg": "rgb(255, 255, 255)",
"filtered_rows": [["1", "Alfreds", "GERMANY", "$19.50"]],
"filter_summary": "john|JOHN|$12.50",
}
cases.append(dict(
name="directives_filters_and_sorted_table",
expected=exp2,
actual=res2,
passed=(res2 == exp2),
))
# Case 3: DOM (ng-disabled/ng-hide), Events (ng-click), Form validation & AngularJS API utilities
page.check("#chk-disable")
btn_disabled = page.locator("#btn-target").is_disabled()
page.click("#btn-toggle")
panel_hidden = page.locator("#toggle-panel").is_hidden()
page.fill("#email-input", "bad-email")
invalid_state = page.locator("#email-state").inner_text()
page.fill("#email-input", "dev@example.com")
valid_state = page.locator("#email-state").inner_text()
api_check = page.evaluate("""() => ({
lower: window.angularApi.lowercase('AngularJS'),
upper: window.angularApi.uppercase('AngularJS'),
isStr: window.angularApi.isString('abc'),
isNum: window.angularApi.isNumber(42),
clicks: window.angularApi.getClicks()
})""")
res3 = {
"btn_disabled": btn_disabled,
"panel_hidden": panel_hidden,
"invalid_state": invalid_state,
"valid_state": valid_state,
**api_check,
}
exp3 = {
"btn_disabled": True,
"panel_hidden": True,
"invalid_state": "dirty:invalid",
"valid_state": "dirty:valid",
"lower": "angularjs",
"upper": "ANGULARJS",
"isStr": True,
"isNum": True,
"clicks": 1,
}
cases.append(dict(
name="dom_events_forms_and_validation",
expected=exp3,
actual=res3,
passed=(res3 == exp3),
))
# Case 4: Todo / Memo application CRUD (add + remove completed)
init_count = page.locator("#todo-list li").count()
page.fill("#todo-input", "复习路由配置")
page.click("#todo-add")
after_add_count = page.locator("#todo-list li").count()
page.click("#todo-remove")
remaining_texts = page.locator("#todo-list li span").all_inner_texts()
res4 = {
"initial_count": init_count,
"after_add_count": after_add_count,
"after_remove_done": remaining_texts,
}
exp4 = {
"initial_count": 2,
"after_add_count": 3,
"after_remove_done": ["编写过滤器表格", "复习路由配置"],
}
cases.append(dict(
name="todo_memo_application_crud",
expected=exp4,
actual=res4,
passed=(res4 == exp4),
))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
AngularJS 仅编译位于 ng-app 根容器内部的 DOM 模板,未纳入引导范围的插值表达式会被浏览器当作普通文本原样展示;AngularJS 1.7.0 移除了 angular.lowercase() 与 angular.uppercase(),应改用原生 JavaScript 的 String.prototype.toLowerCase() 和 toUpperCase()。