蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证控制器属性绑定、fullName() 方法重算及外部控制器脚本加载

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-controllers.py
explore-controllers.py268 行
"""Offline Playwright Chromium lab for AngularJS Ch 07 (controllers)."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright

RUNTIME_JS = r"""
(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];
    }
  };

  function evalExpr(expr, scope) {
    const v = new Function("scope", "with(scope){ return (" + expr + "); }")(scope);
    return v === undefined || v === null ? "" : String(v);
  }

  function renderTree(root, scope) {
    const repeatEls = Array.from(root.querySelectorAll("[ng-repeat]"));
    for (const tplEl of repeatEls) {
      const m = tplEl.getAttribute("ng-repeat").trim().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 cScope = Object.create(scope);
        cScope[itemVar] = item;
        const clone = cloneBase.cloneNode(true);
        renderTree(clone, cScope);
        parent.appendChild(clone);
      }
    }

    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 });
      }
    }
    function render() {
      for (const b of textBindings) {
        b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => evalExpr(ex.trim(), scope));
      }
    }
    root.querySelectorAll("[ng-model]").forEach((el) => {
      const prop = el.getAttribute("ng-model");
      if (scope[prop] !== undefined) el.value = scope[prop];
      el.addEventListener("input", () => {
        scope[prop] = el.value;
        render();
      });
    });
    render();
  }

  window.addEventListener("DOMContentLoaded", () => {
    document.querySelectorAll("[ng-app]").forEach((root) => {
      const appName = root.getAttribute("ng-app");
      const ctrlName = root.getAttribute("ng-controller");
      const scope = {};
      if (modules[appName] && modules[appName]._ctrls[ctrlName]) {
        modules[appName]._ctrls[ctrlName](scope);
      }
      renderTree(root, scope);
    });
  });
})();
"""

PERSON_CTRL_JS = """
angular.module('extPersonApp', []).controller('personCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
  $scope.fullName = function() {
    return $scope.firstName + " " + $scope.lastName;
  };
});
"""

NAMES_CTRL_JS = """
angular.module('extNamesApp', []).controller('namesCtrl', function($scope) {
  $scope.names = [
    { name: 'Jani', country: 'Norway' },
    { name: 'Hege', country: 'Sweden' },
    { name: 'Kai', country: 'Denmark' }
  ];
});
"""

INDEX_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>AngularJS Controllers Offline Lab</title>
  <script src="/mini-angular.js"></script>
</head>
<body>
  <div id="sec-basic" ng-app="basicApp" ng-controller="myCtrl">
    <input id="b-first" type="text" ng-model="firstName">
    <input id="b-last" type="text" ng-model="lastName">
    <p id="b-out">{{firstName + " " + lastName}}</p>
  </div>

  <div id="sec-method" ng-app="methodApp" ng-controller="personMethodCtrl">
    <input id="m-first" type="text" ng-model="firstName">
    <input id="m-last" type="text" ng-model="lastName">
    <p id="m-out">{{fullName()}}</p>
  </div>

  <div id="sec-ext-person" ng-app="extPersonApp" ng-controller="personCtrl">
    <input id="ep-first" type="text" ng-model="firstName">
    <input id="ep-last" type="text" ng-model="lastName">
    <p id="ep-out">{{firstName + " " + lastName}}</p>
  </div>

  <div id="sec-ext-names" ng-app="extNamesApp" ng-controller="namesCtrl">
    <ul id="en-ul"><li ng-repeat="x in names">{{ x.name + ', ' + x.country }}</li></ul>
  </div>

  <script>
    angular.module('basicApp', []).controller('myCtrl', function($scope) {
      $scope.firstName = "John";
      $scope.lastName = "Doe";
    });
    angular.module('methodApp', []).controller('personMethodCtrl', function($scope) {
      $scope.firstName = "John";
      $scope.lastName = "Doe";
      $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
      };
    });
  </script>
  <script src="/personController.js"></script>
  <script src="/namesController.js"></script>
</body>
</html>
"""

ROUTES = {
    "/": ("text/html; charset=utf-8", INDEX_HTML),
    "/mini-angular.js": ("application/javascript; charset=utf-8", RUNTIME_JS),
    "/personController.js": ("application/javascript; charset=utf-8", PERSON_CTRL_JS),
    "/namesController.js": ("application/javascript; charset=utf-8", NAMES_CTRL_JS),
}


class LocalHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path in ROUTES:
            ctype, body = ROUTES[self.path]
            data = body.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)
        else:
            self.send_response(404)
            self.end_headers()

    def log_message(self, format, *args):
        pass


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), LocalHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            page.goto(f"http://127.0.0.1:{port}/", wait_until="load")

            # Case 1: Controller properties & two-way binding
            b_init = page.locator("#b-out").text_content()
            page.fill("#b-first", "Linus")
            page.fill("#b-last", "Torvalds")
            b_upd = page.locator("#b-out").text_content()
            actual_1 = {"initial": b_init, "updated": b_upd}
            expected_1 = {"initial": "John Doe", "updated": "Linus Torvalds"}
            cases.append({
                "name": "controller_properties_and_two_way",
                "expected": expected_1,
                "actual": actual_1,
                "passed": actual_1 == expected_1,
            })

            # Case 2: Controller method fullName()
            m_init = page.locator("#m-out").text_content()
            page.fill("#m-first", "Ada")
            m_upd = page.locator("#m-out").text_content()
            actual_2 = {"initial": m_init, "after_first_edit": m_upd}
            expected_2 = {"initial": "John Doe", "after_first_edit": "Ada Doe"}
            cases.append({
                "name": "controller_method_full_name",
                "expected": expected_2,
                "actual": actual_2,
                "passed": actual_2 == expected_2,
            })

            # Case 3: External personController.js script
            ep_init = page.locator("#ep-out").text_content()
            page.fill("#ep-first", "Alan")
            page.fill("#ep-last", "Turing")
            ep_upd = page.locator("#ep-out").text_content()
            actual_3 = {"initial": ep_init, "updated": ep_upd}
            expected_3 = {"initial": "John Doe", "updated": "Alan Turing"}
            cases.append({
                "name": "external_person_controller_script",
                "expected": expected_3,
                "actual": actual_3,
                "passed": actual_3 == expected_3,
            })

            # Case 4: External namesController.js + ng-repeat
            items = page.locator("#en-ul li").all_text_contents()
            actual_4 = {"count": len(items), "items": items}
            expected_4 = {
                "count": 3,
                "items": ["Jani, Norway", "Hege, Sweden", "Kai, Denmark"],
            }
            cases.append({
                "name": "external_names_controller_ng_repeat",
                "expected": expected_4,
                "actual": actual_4,
                "passed": actual_4 == expected_4,
            })

            browser.close()
    finally:
        server.shutdown()
        server.server_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-controllers-lab/explore-controllers.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-controllers.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AngularJS

课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip

下载课程关联工程包:AngularJS

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a853.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习