"""Offline Playwright Chromium lab for AngularJS Ch 04 (directives)."""
import json
from playwright.sync_api import sync_playwright
HTML_PAGE = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS Directives Offline Lab</title></head>
<body>
<div id="sec-bind" ng-app="" ng-init="firstName='John'">
<input id="fn-inp" type="text" ng-model="firstName">
<p id="fn-out">{{ firstName }}</p>
</div>
<div id="sec-calc" ng-app="" ng-init="quantity=1;price=5">
<input id="qty-inp" type="number" ng-model="quantity">
<input id="price-inp" type="number" ng-model="price">
<p id="total-out">{{ quantity * price }}</p>
</div>
<div id="sec-rep-arr" ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul id="ul-arr">
<li ng-repeat="x in names">{{ x }}</li>
</ul>
</div>
<div id="sec-rep-obj" ng-app="" ng-init="names=[{name:'Jani',country:'Norway'},{name:'Hege',country:'Sweden'},{name:'Kai',country:'Denmark'}]">
<ul id="ul-obj">
<li ng-repeat="x in names">{{ x.name + ', ' + x.country }}</li>
</ul>
</div>
<div id="sec-dir-ea" ng-app="eaApp">
<sky-banner id="ea-elem"></sky-banner>
<div id="ea-attr" sky-banner></div>
<div id="ea-cls" class="sky-banner"></div>
<!-- directive: sky-banner -->
</div>
<div id="sec-dir-eacm" ng-app="eacmApp">
<sky-notice id="eacm-elem"></sky-notice>
<div id="eacm-attr" sky-notice></div>
<div id="eacm-cls" class="sky-notice"></div>
<div id="eacm-comment-wrap"><!-- directive: sky-notice --></div>
</div>
<div id="sec-dir-a" ng-app="aOnlyApp">
<sky-only-attr id="aonly-elem"></sky-only-attr>
<div id="aonly-attr" sky-only-attr></div>
</div>
<script>
(function () {
const modules = {};
window.angular = {
module(name, deps) {
if (deps) {
const mod = { _directives: {} };
mod.directive = function (camelName, factory) {
mod._directives[camelName] = factory();
return mod;
};
modules[name] = mod;
return mod;
}
return modules[name];
}
};
angular.module("eaApp", []).directive("skyBanner", function () {
return { template: "<h1>自定义指令!</h1>" };
});
angular.module("eacmApp", []).directive("skyNotice", function () {
return { restrict: "EACM", replace: true, template: "<h1>四模式指令!</h1>" };
});
angular.module("aOnlyApp", []).directive("skyOnlyAttr", function () {
return { restrict: "A", template: "<h1>仅属性指令!</h1>" };
});
function camelToKebab(str) {
return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
}
function evalExpr(expr, scope) {
const v = new Function("scope", "with(scope){ return (" + expr + "); }")(scope);
return v === undefined || v === null ? "" : String(v);
}
function compileInterpolations(el, scope) {
const textBindings = [];
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let n;
while ((n = walker.nextNode())) {
if (n.nodeValue && n.nodeValue.includes("{{")) {
textBindings.push({ node: n, tpl: n.nodeValue });
}
}
return function render() {
for (const b of textBindings) {
b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => evalExpr(ex.trim(), scope));
}
};
}
function applyDirectives(root, mod) {
for (const [camelName, ddo] of Object.entries(mod._directives)) {
const kebab = camelToKebab(camelName);
const restrict = ddo.restrict || "EA";
if (restrict.includes("E")) {
root.querySelectorAll(kebab).forEach((el) => {
el.innerHTML = ddo.template;
});
}
if (restrict.includes("A")) {
root.querySelectorAll("[" + kebab + "]").forEach((el) => {
el.innerHTML = ddo.template;
});
}
if (restrict.includes("C")) {
root.querySelectorAll("." + kebab).forEach((el) => {
el.innerHTML = ddo.template;
});
}
if (restrict.includes("M")) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
const comments = [];
let c;
while ((c = walker.nextNode())) comments.push(c);
for (const cm of comments) {
const m = cm.nodeValue.trim().match(/^directive:\s*([a-z0-9-]+)$/);
if (m && m[1] === kebab) {
const holder = document.createElement("div");
holder.innerHTML = ddo.template;
if (ddo.replace && holder.firstElementChild) {
cm.parentNode.replaceChild(holder.firstElementChild, cm);
}
}
}
}
}
}
document.querySelectorAll("[ng-app]").forEach((root) => {
const appName = root.getAttribute("ng-app");
if (appName && modules[appName]) {
applyDirectives(root, modules[appName]);
}
const scope = {};
const initCode = root.getAttribute("ng-init");
if (initCode) {
const initProxy = new Proxy(scope, { has: () => true });
new Function("scope", "with(scope){ " + initCode + "; }")(initProxy);
}
const repeatEls = Array.from(root.querySelectorAll("[ng-repeat]"));
for (const tplEl of repeatEls) {
const expr = tplEl.getAttribute("ng-repeat").trim();
const m = expr.match(/^(\w+)\s+in\s+(\w+)$/);
if (!m) continue;
const [, itemVar, listVar] = m;
const parent = tplEl.parentNode;
const items = scope[listVar] || [];
tplEl.removeAttribute("ng-repeat");
const cloneBase = tplEl.cloneNode(true);
parent.removeChild(tplEl);
for (const item of items) {
const childScope = Object.create(scope);
childScope[itemVar] = item;
const clone = cloneBase.cloneNode(true);
compileInterpolations(clone, childScope)();
parent.appendChild(clone);
}
}
const render = compileInterpolations(root, scope);
root.querySelectorAll("[ng-model]").forEach((el) => {
const prop = el.getAttribute("ng-model");
if (scope[prop] !== undefined) el.value = String(scope[prop]);
el.addEventListener("input", () => {
scope[prop] = el.type === "number" ? Number(el.value) : el.value;
render();
});
});
render();
});
})();
</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 two-way binding + price calculator
init_fn = page.locator("#fn-out").text_content()
page.fill("#fn-inp", "Grace")
upd_fn = page.locator("#fn-out").text_content()
init_total = page.locator("#total-out").text_content()
page.fill("#qty-inp", "3")
page.fill("#price-inp", "12")
upd_total = page.locator("#total-out").text_content()
actual_1 = {
"init_first_name": init_fn,
"updated_first_name": upd_fn,
"init_total": init_total,
"updated_total": upd_total,
}
expected_1 = {
"init_first_name": "John",
"updated_first_name": "Grace",
"init_total": "5",
"updated_total": "36",
}
cases.append({
"name": "ng_model_first_name_and_price_calc",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: ng-repeat on string array & object array
actual_2 = {
"string_items": page.locator("#ul-arr li").all_text_contents(),
"object_items": page.locator("#ul-obj li").all_text_contents(),
}
expected_2 = {
"string_items": ["Jani", "Hege", "Kai"],
"object_items": ["Jani, Norway", "Hege, Sweden", "Kai, Denmark"],
}
cases.append({
"name": "ng_repeat_primitive_and_object_arrays",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: default restrict="EA" matches element & attribute, ignores class & comment
actual_3 = {
"element": page.locator("#ea-elem").text_content().strip(),
"attribute": page.locator("#ea-attr").text_content().strip(),
"class_ignored": page.locator("#ea-cls").text_content().strip(),
"h1_count": page.locator("#sec-dir-ea h1").count(),
}
expected_3 = {
"element": "自定义指令!",
"attribute": "自定义指令!",
"class_ignored": "",
"h1_count": 2,
}
cases.append({
"name": "custom_directive_camel_to_kebab_ea",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: restrict="EACM" supports element, attribute, class, comment
actual_4 = {
"element": page.locator("#eacm-elem").text_content().strip(),
"attribute": page.locator("#eacm-attr").text_content().strip(),
"class": page.locator("#eacm-cls").text_content().strip(),
"comment": page.locator("#eacm-comment-wrap").text_content().strip(),
}
expected_4 = {
"element": "四模式指令!",
"attribute": "四模式指令!",
"class": "四模式指令!",
"comment": "四模式指令!",
}
cases.append({
"name": "custom_directive_four_modes_eacm",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: restrict="A" restricts to attribute only
actual_5 = {
"element_ignored": page.locator("#aonly-elem").text_content().strip(),
"attribute_matched": page.locator("#aonly-attr").text_content().strip(),
}
expected_5 = {
"element_ignored": "",
"attribute_matched": "仅属性指令!",
}
cases.append({
"name": "custom_directive_restrict_a_only",
"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-directives-lab/explore-directives.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-directives.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a855.zip