"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/angularjs-intro-lab/explore-intro.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-intro.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a864.zip