AngularJS 事件
核对 AngularJS 事件指令 ng-click 的表达式求值与控制器方法调用,以及联动 ng-hide 与 ng-show 切换视图区域的离线 Chromium 实测。
学完这一章,你能够
- 核对 AngularJS 事件指令 ng-click 的表达式求值与控制器方法调用,以及联动 ng-hide 与 ng-show 切换视图区域的离线 Chromium 实测。
使用 ng-click 响应点击事件
AngularJS 内置了专属的 HTML 事件指令集合,其中最常用的是定义点击交互行为的 `ng-click`。既可以在 `ng-click` 属性中直接编写内联作用域表达式(如 `ng-click="count = count + 1"`,AngularJS 表达式引擎在未初始化 `count` 时会将其按 `0` 累加),也可以调用控制器暴露的方法并在执行后自动触发脏检查更新视图。本站离线 Chromium 实测:初始计数输出为空字符串,点击 1 次变为 `1`,累计点击 3 次准确显示 `3`。
结合 ng-click 与 ng-hide 隐藏表单区域
`ng-hide` 指令根据布尔值控制页面局部是否隐藏:`ng-hide="true"` 使元素不可见,`ng-hide="false"` 保持可见。将其与按钮上的 `ng-click="toggle()"` 配合,就能实现交互式折叠面板。
在 `personCtrl` 控制器示例中,模型初始化为 `$scope.firstName = "John"`、`$scope.lastName = "Doe"` 与默认标志 `$scope.myVar = false`,并定义 `$scope.toggle = function() { $scope.myVar = !$scope.myVar; }`(注意多条赋值语句间应使用标准分号分隔)。`<p ng-hide="myVar">` 包裹两个绑定 `firstName`/`lastName` 的输入框与拼接插值。本站离线 Chromium 实测:初始 `display` 为 `block`、全名显示 `John Doe`,将名改为 `Alice` 后即刻联动为 `Alice Doe`;首次点击切换按钮使 `myVar` 变为 `true`、区域隐藏为 `none`,再次点击则恢复 `block`。
结合 ng-click 与 ng-show 显示表单区域
同理,也可以使用 `ng-show` 达到相反的布尔语义:`ng-show="true"` 显示元素、`ng-show="false"` 隐藏元素。在对应 `personCtrl` 实例中将初始值设为 `$scope.myVar = true`,配合 `<p ng-show="myVar">` 与 `toggle()` 翻转布尔标志即可在初始可见与隐藏状态间来回切换。本站离线 Chromium 实测:初始 `display` 为 `block`,首次点击切换按钮后变为 `none`,第二次点击恢复为 `block`,随后将姓修改为 `Smith` 时视图同步输出 `John Smith`。
离线 Chromium 核验 ng-click 递增计数及 personCtrl 联动 ng-hide/ng-show 切换
展开查看收起
"""Offline Playwright Chromium lab for AngularJS Ch 15: html-events."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS Events Lab</title>
<style>.ng-hide { display: none !important; }</style>
</head>
<body>
<div id="sec-click">
<button id="btn-count">点我!</button>
<p id="out-count"></p>
</div>
<div id="sec-hide">
<button id="btn-toggle-hide">隐藏/显示</button>
<p id="panel-hide">
名: <input id="hide-first" type="text"><br>
姓: <input id="hide-last" type="text"><br>
Full Name: <span id="hide-fullname"></span>
</p>
</div>
<div id="sec-show">
<button id="btn-toggle-show">隐藏/显示</button>
<p id="panel-show">
名: <input id="show-first" type="text"><br>
姓: <input id="show-last" type="text"><br>
姓名: <span id="show-fullname"></span>
</p>
</div>
<script>
(function () {
// 1. ng-click="count = count + 1" (AngularJS treats undefined + 1 as 1)
let count;
const outCount = document.getElementById("out-count");
document.getElementById("btn-count").addEventListener("click", () => {
count = (count || 0) + 1;
outCount.textContent = String(count);
});
// 2. ng-hide="myVar" with initial myVar = false
const hideScope = { firstName: "John", lastName: "Doe", myVar: false };
const hideFirst = document.getElementById("hide-first");
const hideLast = document.getElementById("hide-last");
const hideFull = document.getElementById("hide-fullname");
const panelHide = document.getElementById("panel-hide");
function renderHide() {
hideFirst.value = hideScope.firstName;
hideLast.value = hideScope.lastName;
hideFull.textContent = hideScope.firstName + " " + hideScope.lastName;
panelHide.classList.toggle("ng-hide", !!hideScope.myVar);
}
document.getElementById("btn-toggle-hide").addEventListener("click", () => {
hideScope.myVar = !hideScope.myVar;
renderHide();
});
hideFirst.addEventListener("input", () => { hideScope.firstName = hideFirst.value; renderHide(); });
hideLast.addEventListener("input", () => { hideScope.lastName = hideLast.value; renderHide(); });
renderHide();
// 3. ng-show="myVar" with initial myVar = true
const showScope = { firstName: "John", lastName: "Doe", myVar: true };
const showFirst = document.getElementById("show-first");
const showLast = document.getElementById("show-last");
const showFull = document.getElementById("show-fullname");
const panelShow = document.getElementById("panel-show");
function renderShow() {
showFirst.value = showScope.firstName;
showLast.value = showScope.lastName;
showFull.textContent = showScope.firstName + " " + showScope.lastName;
panelShow.classList.toggle("ng-hide", !showScope.myVar);
}
document.getElementById("btn-toggle-show").addEventListener("click", () => {
showScope.myVar = !showScope.myVar;
renderShow();
});
showFirst.addEventListener("input", () => { showScope.firstName = showFirst.value; renderShow(); });
showLast.addEventListener("input", () => { showScope.lastName = showLast.value; renderShow(); });
renderShow();
})();
</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(HTML_DOC)
# Case 1: ng-click counter increment
before = page.text_content("#out-count")
page.click("#btn-count")
after1 = page.text_content("#out-count")
page.click("#btn-count")
page.click("#btn-count")
after3 = page.text_content("#out-count")
actual1 = {"initial": before, "after_1_click": after1, "after_3_clicks": after3}
expected1 = {"initial": "", "after_1_click": "1", "after_3_clicks": "3"}
cases.append({"name": "ng_click_counter_increment", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})
# Case 2: ng-hide toggle + two-way personCtrl binding
init_vis = page.evaluate('getComputedStyle(document.getElementById("panel-hide")).display')
init_name = page.text_content("#hide-fullname")
page.fill("#hide-first", "Alice")
updated_name = page.text_content("#hide-fullname")
page.click("#btn-toggle-hide")
hidden_vis = page.evaluate('getComputedStyle(document.getElementById("panel-hide")).display')
page.click("#btn-toggle-hide")
restored_vis = page.evaluate('getComputedStyle(document.getElementById("panel-hide")).display')
actual2 = {
"initial_display": init_vis,
"initial_fullname": init_name,
"updated_fullname": updated_name,
"after_first_toggle": hidden_vis,
"after_second_toggle": restored_vis,
}
expected2 = {
"initial_display": "block",
"initial_fullname": "John Doe",
"updated_fullname": "Alice Doe",
"after_first_toggle": "none",
"after_second_toggle": "block",
}
cases.append({"name": "ng_hide_toggle_and_person_binding", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})
# Case 3: ng-show toggle with initial myVar = true
s_init = page.evaluate('getComputedStyle(document.getElementById("panel-show")).display')
page.click("#btn-toggle-show")
s_hidden = page.evaluate('getComputedStyle(document.getElementById("panel-show")).display')
page.click("#btn-toggle-show")
s_shown = page.evaluate('getComputedStyle(document.getElementById("panel-show")).display')
page.fill("#show-last", "Smith")
s_name = page.text_content("#show-fullname")
actual3 = {
"initial_display": s_init,
"after_first_toggle": s_hidden,
"after_second_toggle": s_shown,
"updated_fullname": s_name,
}
expected3 = {
"initial_display": "block",
"after_first_toggle": "none",
"after_second_toggle": "block",
"updated_fullname": "John Smith",
}
cases.append({"name": "ng_show_toggle_and_person_binding", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
使用 ng-hide="myVar" 时需将初始值设为 true(满足隐藏条件);使用 ng-show="myVar" 时则应设为 false(不满足显示条件)。