"""Offline Playwright Chromium lab for AngularJS Ch 11: select."""
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 Select Lab</title></head>
<body>
<div id="case-basic">
<select id="sel-names"></select>
<span id="out-basic"></span>
</div>
<div id="case-repeat-vs-options">
<select id="sel-repeat"></select>
<h1 id="out-repeat"></h1>
<select id="sel-options"></select>
<h1 id="out-opt-site"></h1>
<p id="out-opt-url"></p>
</div>
<div id="case-object-source">
<select id="sel-obj-str"></select>
<h1 id="out-obj-str"></h1>
</div>
<div id="case-object-nested">
<select id="sel-car-key"></select>
<div id="out-car-key"></div>
<select id="sel-car-brand"></select>
<div id="out-car-brand"></div>
</div>
<script>
// Minimal offline AngularJS 1.x ng-options / ng-repeat equivalence harness
(function () {
const names = ["Google", "BlueSky", "Taobao"];
const sitesArr = [
{ site: "Google", url: "https://www.google.com" },
{ site: "BlueSky", url: "https://example.org/bluesky" },
{ site: "Taobao", url: "https://www.taobao.com" }
];
const sitesObj = { site01: "Google", site02: "BlueSky", site03: "Taobao" };
const carsObj = {
car01: { brand: "Ford", model: "Mustang", color: "red" },
car02: { brand: "Fiat", model: "500", color: "white" },
car03: { brand: "Volvo", model: "XC90", color: "black" }
};
const state = {
selectedName: names[0], // ng-init="selectedName = names[0]"
selectedRepeat: null,
selectedSiteObj: null,
selectedObjStr: null,
selectedCarKey: null,
selectedCarBrand: null
};
// 1. ng-options="x for x in names" with ng-init
const selNames = document.getElementById("sel-names");
names.forEach((n, idx) => {
const opt = document.createElement("option");
opt.value = "string:" + n;
opt.textContent = n;
if (n === state.selectedName) opt.selected = true;
selNames.appendChild(opt);
});
const renderBasic = () => {
document.getElementById("out-basic").textContent = state.selectedName;
};
selNames.addEventListener("change", () => {
const idx = selNames.selectedIndex;
state.selectedName = names[idx];
renderBasic();
});
renderBasic();
// 2a. ng-repeat="x in sites" value="{{x.url}}" (binds string only)
const selRepeat = document.getElementById("sel-repeat");
sitesArr.forEach((item) => {
const opt = document.createElement("option");
opt.value = item.url;
opt.textContent = item.site;
selRepeat.appendChild(opt);
});
selRepeat.addEventListener("change", () => {
state.selectedRepeat = selRepeat.value;
document.getElementById("out-repeat").textContent = "你选择的是: " + state.selectedRepeat;
});
// 2b. ng-options="x.site for x in sites" (binds full JS object)
const selOptions = document.getElementById("sel-options");
sitesArr.forEach((item, idx) => {
const opt = document.createElement("option");
opt.value = "object:" + idx;
opt.textContent = item.site;
selOptions.appendChild(opt);
});
selOptions.addEventListener("change", () => {
state.selectedSiteObj = sitesArr[selOptions.selectedIndex];
document.getElementById("out-opt-site").textContent = "你选择的是: " + state.selectedSiteObj.site;
document.getElementById("out-opt-url").textContent = "网址为: " + state.selectedSiteObj.url;
});
// 3. ng-options="x for (x, y) in sitesObj" (label = key x, value = y)
const selObjStr = document.getElementById("sel-obj-str");
const siteEntries = Object.entries(sitesObj);
siteEntries.forEach(([k, v]) => {
const opt = document.createElement("option");
opt.value = k;
opt.textContent = k;
selObjStr.appendChild(opt);
});
selObjStr.addEventListener("change", () => {
const [, v] = siteEntries[selObjStr.selectedIndex];
state.selectedObjStr = v;
document.getElementById("out-obj-str").textContent = "你选择的值是: " + state.selectedObjStr;
});
// 4a. ng-options="x for (x, y) in carsObj" (label = key x, value = object y)
const selCarKey = document.getElementById("sel-car-key");
const carEntries = Object.entries(carsObj);
carEntries.forEach(([k]) => {
const opt = document.createElement("option");
opt.value = k;
opt.textContent = k;
selCarKey.appendChild(opt);
});
selCarKey.addEventListener("change", () => {
const [, y] = carEntries[selCarKey.selectedIndex];
state.selectedCarKey = y;
document.getElementById("out-car-key").textContent =
y.brand + "|" + y.model + "|" + y.color;
});
// 4b. ng-options="y.brand for (x, y) in carsObj" (label = y.brand, value = object y)
const selCarBrand = document.getElementById("sel-car-brand");
carEntries.forEach(([k, y]) => {
const opt = document.createElement("option");
opt.value = k;
opt.textContent = y.brand;
selCarBrand.appendChild(opt);
});
selCarBrand.addEventListener("change", () => {
const [, y] = carEntries[selCarBrand.selectedIndex];
state.selectedCarBrand = y;
document.getElementById("out-car-brand").textContent =
y.brand + "|" + y.model + "|" + y.color;
});
window.__labState = state;
})();
</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-options array + ng-init default selection + change
init_val = page.text_content("#out-basic")
init_opts = page.eval_on_selector_all("#sel-names option", "els => els.map(e => e.textContent)")
page.select_option("#sel-names", index=2)
after_val = page.text_content("#out-basic")
actual1 = {"options": init_opts, "initial": init_val, "after_select_2": after_val}
expected1 = {"options": ["Google", "BlueSky", "Taobao"], "initial": "Google", "after_select_2": "Taobao"}
cases.append({"name": "ng_options_array_and_ng_init", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})
# Case 2: ng-repeat binds string value vs ng-options binds object
page.select_option("#sel-repeat", index=1)
page.select_option("#sel-options", index=1)
actual2 = page.evaluate("""() => ({
repeatType: typeof window.__labState.selectedRepeat,
repeatValue: window.__labState.selectedRepeat,
repeatDom: document.getElementById("out-repeat").textContent,
optionsType: typeof window.__labState.selectedSiteObj,
optionsObj: window.__labState.selectedSiteObj,
optionsSiteDom: document.getElementById("out-opt-site").textContent,
optionsUrlDom: document.getElementById("out-opt-url").textContent
})""")
expected2 = {
"repeatType": "string",
"repeatValue": "https://example.org/bluesky",
"repeatDom": "你选择的是: https://example.org/bluesky",
"optionsType": "object",
"optionsObj": {"site": "BlueSky", "url": "https://example.org/bluesky"},
"optionsSiteDom": "你选择的是: BlueSky",
"optionsUrlDom": "网址为: https://example.org/bluesky",
}
cases.append({"name": "ng_repeat_string_vs_ng_options_object", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})
# Case 3: object data source (key as label, value as model)
obj_labels = page.eval_on_selector_all("#sel-obj-str option", "els => els.map(e => e.textContent)")
page.select_option("#sel-obj-str", index=1)
actual3 = {
"labels": obj_labels,
"selected_value": page.evaluate("window.__labState.selectedObjStr"),
"dom": page.text_content("#out-obj-str"),
}
expected3 = {
"labels": ["site01", "site02", "site03"],
"selected_value": "BlueSky",
"dom": "你选择的值是: BlueSky",
}
cases.append({"name": "object_source_key_label_value_model", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})
# Case 4: object-of-objects with key label vs nested property y.brand label
key_labels = page.eval_on_selector_all("#sel-car-key option", "els => els.map(e => e.textContent)")
brand_labels = page.eval_on_selector_all("#sel-car-brand option", "els => els.map(e => e.textContent)")
page.select_option("#sel-car-key", index=0)
page.select_option("#sel-car-brand", index=2)
actual4 = {
"key_labels": key_labels,
"key_selected_dom": page.text_content("#out-car-key"),
"brand_labels": brand_labels,
"brand_selected_dom": page.text_content("#out-car-brand"),
"brand_selected_obj": page.evaluate("window.__labState.selectedCarBrand"),
}
expected4 = {
"key_labels": ["car01", "car02", "car03"],
"key_selected_dom": "Ford|Mustang|red",
"brand_labels": ["Ford", "Fiat", "Volvo"],
"brand_selected_dom": "Volvo|XC90|black",
"brand_selected_obj": {"brand": "Volvo", "model": "XC90", "color": "black"},
}
cases.append({"name": "object_nested_value_and_property_label", "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-select-lab/explore-select.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-select.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a869.zip