"""Offline Playwright Chromium lab for AngularJS Ch 03 (expressions)."""
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 Expressions Offline Lab</title></head>
<body>
<div id="sec-num" ng-app="" ng-init="quantity=1;cost=5">
<p id="num-interp">总价:{{ quantity * cost }}</p>
<p id="num-bind">总价:<span id="num-bind-val" ng-bind="quantity * cost"></span></p>
</div>
<div id="sec-str" ng-app="" ng-init="firstName='John';lastName='Doe'">
<p id="str-interp">{{ firstName + " " + lastName }}</p>
<span id="str-bind" ng-bind="firstName + ' ' + lastName"></span>
</div>
<div id="sec-obj" ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p id="obj-interp">{{ person.lastName }}</p>
<span id="obj-bind" ng-bind="person.lastName"></span>
</div>
<div id="sec-arr" ng-app="" ng-init="points=[1,15,19,2,40]">
<p id="arr-interp">{{ points[2] }}</p>
<span id="arr-bind" ng-bind="points[2]"></span>
</div>
<div id="sec-diff" ng-app="" ng-init="label='angular'">
<p id="diff-filter">{{ label | uppercase }}</p>
<p id="diff-missing">{{ missingObj.deepProp }}</p>
</div>
<script>
(function () {
const filters = {
uppercase: (v) => String(v).toUpperCase(),
lowercase: (v) => String(v).toLowerCase(),
};
const FORBIDDEN_RE = /\b(if|else|for|while|do|switch|try|catch|throw|function)\b/;
function safeEvalNgExpr(rawExpr, scope) {
if (FORBIDDEN_RE.test(rawExpr)) {
throw new Error("Disallowed JS statement in AngularJS expression");
}
const parts = rawExpr.split("|").map((s) => s.trim());
let val;
try {
const fn = new Function("scope", "with(scope){ return (" + parts[0] + "); }");
val = fn(scope);
} catch (_) {
val = undefined;
}
for (let i = 1; i < parts.length; i++) {
const f = filters[parts[i]];
if (f) val = f(val);
}
return val === undefined || val === null ? "" : String(val);
}
window.__testNgExpr = safeEvalNgExpr;
document.querySelectorAll("[ng-app]").forEach((root) => {
const scope = {};
const initCode = root.getAttribute("ng-init");
if (initCode) {
const initProxy = new Proxy(scope, { has: () => true });
new Function("scope", "with(scope){ " + initCode + "; }")(initProxy);
}
root.__scope = 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]"));
root.__render = function () {
for (const b of textBindings) {
b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => safeEvalNgExpr(ex.trim(), scope));
}
for (const el of bindEls) {
el.textContent = safeEvalNgExpr(el.getAttribute("ng-bind"), scope);
}
};
root.__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: Numbers interpolation vs ng-bind + dynamic update
init_interp = page.locator("#num-interp").text_content()
init_bind = page.locator("#num-bind-val").text_content()
page.evaluate("""() => {
const r = document.getElementById('sec-num');
r.__scope.quantity = 4;
r.__render();
}""")
updated_interp = page.locator("#num-interp").text_content()
updated_bind = page.locator("#num-bind-val").text_content()
actual_1 = {
"init_interp": init_interp,
"init_bind": init_bind,
"updated_interp": updated_interp,
"updated_bind": updated_bind,
}
expected_1 = {
"init_interp": "总价:5",
"init_bind": "5",
"updated_interp": "总价:20",
"updated_bind": "20",
}
cases.append({
"name": "expression_numbers_interp_vs_ng_bind",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Strings concatenation
actual_2 = {
"interp": page.locator("#str-interp").text_content(),
"ng_bind": page.locator("#str-bind").text_content(),
}
expected_2 = {"interp": "John Doe", "ng_bind": "John Doe"}
cases.append({
"name": "expression_strings_concat",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Objects property lookup
actual_3 = {
"interp": page.locator("#obj-interp").text_content(),
"ng_bind": page.locator("#obj-bind").text_content(),
}
expected_3 = {"interp": "Doe", "ng_bind": "Doe"}
cases.append({
"name": "expression_objects_property",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Arrays element indexing
actual_4 = {
"interp": page.locator("#arr-interp").text_content(),
"ng_bind": page.locator("#arr-bind").text_content(),
}
expected_4 = {"interp": "19", "ng_bind": "19"}
cases.append({
"name": "expression_arrays_index",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: AngularJS vs JS expression differences
rejected = page.evaluate("""() => {
const results = {};
for (const expr of ['if (true) { 1 }', 'for (var i=0;i<2;i++) {}', 'throw new Error("x")']) {
try {
window.__testNgExpr(expr, {});
results[expr] = false;
} catch (e) {
results[expr] = true;
}
}
return results;
}""")
actual_5 = {
"filter_uppercase": page.locator("#diff-filter").text_content(),
"forgiving_undefined": page.locator("#diff-missing").text_content(),
"disallows_if_for_throw": all(rejected.values()),
}
expected_5 = {
"filter_uppercase": "ANGULAR",
"forgiving_undefined": "",
"disallows_if_for_throw": True,
}
cases.append({
"name": "expression_limits_and_filter_diff",
"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-expressions-lab/explore-expressions.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-expressions.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a857.zip