"""Offline Playwright Chromium lab for AngularJS Ch 16: modules."""
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 Modules Lab</title>
<script>
// Minimal offline AngularJS 1.x module / controller / directive registry equivalence
window.angular = (function () {
const modules = Object.create(null);
function toKebab(name) {
return name.replace(/([A-Z])/g, "-$1").toLowerCase();
}
function module(name, requires) {
if (Array.isArray(requires)) {
const mod = {
name,
requires: requires.slice(),
controllers: Object.create(null),
directives: Object.create(null),
controller(cName, fn) { this.controllers[cName] = fn; return this; },
directive(dName, factory) { this.directives[toKebab(dName)] = factory; return this; }
};
modules[name] = mod;
return mod;
}
if (!modules[name]) throw new Error("Module not found: " + name);
return modules[name];
}
function bootstrap(root) {
const appName = root.getAttribute("ng-app");
const mod = modules[appName];
if (!mod) throw new Error("Unknown ng-app: " + appName);
const scope = Object.create(null);
const ctrlName = root.getAttribute("ng-controller");
if (ctrlName && mod.controllers[ctrlName]) {
mod.controllers[ctrlName](scope);
}
// Render custom attribute directives
for (const [attr, factory] of Object.entries(mod.directives)) {
const targets = [];
if (root.hasAttribute(attr)) targets.push(root);
root.querySelectorAll("[" + attr + "]").forEach((el) => targets.push(el));
targets.forEach((el) => {
const def = factory();
if (def && typeof def.template === "string") el.innerHTML = def.template;
});
}
// Interpolate {{ firstName + " " + lastName }}
root.querySelectorAll("[data-bind='fullname']").forEach((el) => {
el.textContent = scope.firstName + " " + scope.lastName;
});
return { mod, scope };
}
return { module, bootstrap };
})();
</script>
</head>
<body>
<div id="app-ctrl" ng-app="myApp" ng-controller="myCtrl">
<span data-bind="fullname"></span>
</div>
<div id="app-dir" ng-app="dirApp" demo-directive></div>
<div id="app-dep" ng-app="mainApp" ng-controller="splitCtrl">
<span data-bind="fullname"></span>
</div>
<script>
// Case 1: module + controller (no global controller function leaked to window)
(function () {
const app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
})();
// Case 2: module + custom directive (camelCase -> kebab-case)
(function () {
const app = angular.module("dirApp", []);
app.directive("demoDirective", function () {
return { template: "我在指令构造器中创建!" };
});
})();
// Case 3: simulated split files (myApp.js defines module with deps, myCtrl.js retrieves module without [])
(function myAppJs() {
angular.module("sharedLib", []);
angular.module("mainApp", ["sharedLib"]);
})();
(function myCtrlJs() {
angular.module("mainApp").controller("splitCtrl", function ($scope) {
$scope.firstName = "Jane";
$scope.lastName = "Smith";
});
})();
window.__bootResults = {
ctrl: angular.bootstrap(document.getElementById("app-ctrl")),
dir: angular.bootstrap(document.getElementById("app-dir")),
dep: angular.bootstrap(document.getElementById("app-dep"))
};
</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: Module creation, controller rendering, and global namespace isolation
actual1 = page.evaluate("""() => ({
rendered: document.querySelector("#app-ctrl [data-bind='fullname']").textContent,
requires: window.__bootResults.ctrl.mod.requires,
globalMyCtrlType: typeof window.myCtrl,
angularLoadedInHead: document.head.querySelectorAll("script").length === 1
})""")
expected1 = {
"rendered": "John Doe",
"requires": [],
"globalMyCtrlType": "undefined",
"angularLoadedInHead": True,
}
cases.append({"name": "module_controller_and_namespace_isolation", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})
# Case 2: Custom directive camelCase-to-kebab-case registration
actual2 = {
"directive_text": page.text_content("#app-dir"),
"registered_attr": page.evaluate("Object.keys(window.__bootResults.dir.mod.directives)"),
}
expected2 = {
"directive_text": "我在指令构造器中创建!",
"registered_attr": ["demo-directive"],
}
cases.append({"name": "module_custom_directive_normalization", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})
# Case 3: Split file module declaration vs getter & dependency array
actual3 = page.evaluate("""() => ({
rendered: document.querySelector("#app-dep [data-bind='fullname']").textContent,
dependencies: window.__bootResults.dep.mod.requires,
missingModuleThrows: (() => {
try { angular.module("doesNotExist"); return false; }
catch (e) { return e.message.includes("Module not found"); }
})()
})""")
expected3 = {
"rendered": "Jane Smith",
"dependencies": ["sharedLib"],
"missingModuleThrows": True,
}
cases.append({"name": "module_split_files_and_dependencies", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})
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-modules-lab/explore-modules.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-modules.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a866.zip