"""Offline Playwright Chromium lab for AngularJS Ch 17: forms."""
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 Forms Lab</title>
<style>.ng-hide { display: none !important; }</style>
</head>
<body>
<section id="sec-text">
<form>First Name: <input id="in-firstname" type="text"></form>
<h1 id="out-firstname"></h1>
</section>
<section id="sec-checkbox">
<form><input id="chk-header" type="checkbox"></form>
<h1 id="chk-target" class="ng-hide">My Header</h1>
</section>
<section id="sec-radio">
<form>
<input id="rad-dogs" type="radio" name="topic" value="dogs">Dogs
<input id="rad-tuts" type="radio" name="topic" value="tuts">Tutorials
<input id="rad-cars" type="radio" name="topic" value="cars">Cars
</form>
<div id="out-radio"></div>
</section>
<section id="sec-select">
<form>
<select id="sel-topic">
<option value=""></option>
<option value="dogs">Dogs</option>
<option value="tuts">Tutorials</option>
<option value="cars">Cars</option>
</select>
</form>
<div id="out-select"></div>
</section>
<section id="sec-form-reset">
<form id="user-form" novalidate>
<input id="u-first" type="text">
<input id="u-last" type="text">
<button id="btn-reset" type="button">RESET</button>
</form>
<p id="out-form-user"></p>
<p id="out-form-master"></p>
</section>
<script>
(function () {
function angularCopy(src) {
return JSON.parse(JSON.stringify(src));
}
// 1. text input binding
const textScope = { firstname: "John" };
const inFirst = document.getElementById("in-firstname");
const outFirst = document.getElementById("out-firstname");
const renderText = () => {
inFirst.value = textScope.firstname;
outFirst.textContent = "You entered: " + textScope.firstname;
};
inFirst.addEventListener("input", () => { textScope.firstname = inFirst.value; renderText(); });
renderText();
// 2. checkbox binding -> ng-show
const chk = document.getElementById("chk-header");
const chkTarget = document.getElementById("chk-target");
chk.addEventListener("change", () => {
chkTarget.classList.toggle("ng-hide", !chk.checked);
});
// 3. radio binding
const outRadio = document.getElementById("out-radio");
document.querySelectorAll("input[name='topic']").forEach((r) => {
r.addEventListener("change", () => {
if (r.checked) outRadio.textContent = r.value;
});
});
// 4. select binding
const sel = document.getElementById("sel-topic");
const outSel = document.getElementById("out-select");
sel.addEventListener("change", () => { outSel.textContent = sel.value; });
// 5. form reset with angular.copy(master) & novalidate
const formScope = {
master: { firstName: "John", lastName: "Doe" },
user: null
};
const uFirst = document.getElementById("u-first");
const uLast = document.getElementById("u-last");
const outUser = document.getElementById("out-form-user");
const outMaster = document.getElementById("out-form-master");
function renderForm() {
uFirst.value = formScope.user.firstName;
uLast.value = formScope.user.lastName;
outUser.textContent = "form = " + JSON.stringify(formScope.user);
outMaster.textContent = "master = " + JSON.stringify(formScope.master);
}
function reset() {
formScope.user = angularCopy(formScope.master);
renderForm();
}
uFirst.addEventListener("input", () => { formScope.user.firstName = uFirst.value; renderForm(); });
uLast.addEventListener("input", () => { formScope.user.lastName = uLast.value; renderForm(); });
document.getElementById("btn-reset").addEventListener("click", reset);
reset();
window.__formScope = formScope;
})();
</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: text input ng-model two-way binding
init_h1 = page.text_content("#out-firstname")
page.fill("#in-firstname", "Alice")
after_h1 = page.text_content("#out-firstname")
actual1 = {"initial": init_h1, "after_input": after_h1}
expected1 = {"initial": "You entered: John", "after_input": "You entered: Alice"}
cases.append({"name": "text_input_ng_model_binding", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})
# Case 2: checkbox boolean ng-model + ng-show
before_chk = page.evaluate('getComputedStyle(document.getElementById("chk-target")).display')
page.check("#chk-header")
after_chk = page.evaluate('getComputedStyle(document.getElementById("chk-target")).display')
page.uncheck("#chk-header")
unchecked = page.evaluate('getComputedStyle(document.getElementById("chk-target")).display')
actual2 = {"initial": before_chk, "checked": after_chk, "unchecked": unchecked}
expected2 = {"initial": "none", "checked": "block", "unchecked": "none"}
cases.append({"name": "checkbox_boolean_ng_show", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})
# Case 3: radio group and select dropdown ng-model binding
page.check("#rad-tuts")
rad_tuts = page.text_content("#out-radio")
page.check("#rad-cars")
rad_cars = page.text_content("#out-radio")
page.select_option("#sel-topic", "dogs")
sel_dogs = page.text_content("#out-select")
actual3 = {"radio_1": rad_tuts, "radio_2": rad_cars, "select": sel_dogs}
expected3 = {"radio_1": "tuts", "radio_2": "cars", "select": "dogs"}
cases.append({"name": "radio_and_select_ng_model", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})
# Case 4: complete form novalidate + angular.copy(master) reset isolation
has_novalidate = page.evaluate('document.getElementById("user-form").noValidate')
page.fill("#u-first", "Grace")
page.fill("#u-last", "Hopper")
edited = {
"user": page.evaluate("window.__formScope.user"),
"master": page.evaluate("window.__formScope.master"),
"distinct_ref": page.evaluate("window.__formScope.user !== window.__formScope.master"),
}
page.click("#btn-reset")
after_reset = {
"user": page.evaluate("window.__formScope.user"),
"master": page.evaluate("window.__formScope.master"),
"dom_user": page.text_content("#out-form-user"),
}
actual4 = {"novalidate": has_novalidate, "edited": edited, "after_reset": after_reset}
expected4 = {
"novalidate": True,
"edited": {
"user": {"firstName": "Grace", "lastName": "Hopper"},
"master": {"firstName": "John", "lastName": "Doe"},
"distinct_ref": True,
},
"after_reset": {
"user": {"firstName": "John", "lastName": "Doe"},
"master": {"firstName": "John", "lastName": "Doe"},
"dom_user": 'form = {"firstName":"John","lastName":"Doe"}',
},
}
cases.append({"name": "form_novalidate_and_angular_copy_reset", "expected": expected4, "actual": actual4, "passed": actual4 == expected4})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/angularjs-forms-lab/explore-forms.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-forms.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a859.zip