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

验证 $scope 属性映射、ng-click 联动、ng-repeat 子作用域隔离及 $rootScope 继承

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

HTML_PAGE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS Scopes Offline Lab</title></head>
<body>
  <div id="sec-basic" ng-app="app1" ng-controller="carCtrl">
    <h1 id="car-out">{{carname}}</h1>
  </div>

  <div id="sec-mvc" ng-app="app2" ng-controller="greetCtrl">
    <input id="mvc-inp" ng-model="name">
    <h1 id="mvc-greeting">{{greeting}}</h1>
    <button id="mvc-btn" ng-click="sayHello()">点我</button>
  </div>

  <div id="sec-repeat" ng-app="app3" ng-controller="listCtrl">
    <ul id="repeat-ul"><li ng-repeat="x in names">{{x}}</li></ul>
  </div>

  <div id="sec-root" ng-app="app4">
    <div id="ctrl-a" ng-controller="familyCtrl">
      <h1 id="root-title">{{lastname}} 家族成员:</h1>
      <ul id="root-ul"><li ng-repeat="x in names">{{x}} {{lastname}}</li></ul>
    </div>
    <div id="ctrl-b" ng-controller="siblingCtrl">
      <p id="sibling-last">{{lastname}}</p>
      <p id="sibling-shadow">{{ownTag}}</p>
    </div>
  </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];
        }
      };

      angular.module("app1", []).controller("carCtrl", function ($scope) {
        $scope.carname = "Volvo";
      });

      angular.module("app2", []).controller("greetCtrl", function ($scope) {
        $scope.name = "BlueSky";
        $scope.sayHello = function () {
          $scope.greeting = "Hello " + $scope.name + "!";
        };
      });

      angular.module("app3", []).controller("listCtrl", function ($scope) {
        $scope.names = ["Emil", "Tobias", "Linus"];
      });

      const app4 = angular.module("app4", []);
      app4.controller("familyCtrl", function ($scope, $rootScope) {
        $scope.names = ["Emil", "Tobias", "Linus"];
        $rootScope.lastname = "Refsnes";
      });
      app4.controller("siblingCtrl", function ($scope) {
        $scope.ownTag = "inherited:" + $scope.lastname;
      });

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

      function bindElementTree(container, scope) {
        const repeatEls = Array.from(container.querySelectorAll("[ng-repeat]"));
        const childScopes = [];
        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;
            childScopes.push(cScope);
            const clone = cloneBase.cloneNode(true);
            bindElementTree(clone, cScope);
            parent.appendChild(clone);
          }
        }
        container.__childScopes = childScopes;

        const textBindings = [];
        const walker = document.createTreeWalker(container, 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));
          }
        }
        container.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();
          });
        });
        container.querySelectorAll("[ng-click]").forEach((el) => {
          const callExpr = el.getAttribute("ng-click");
          el.addEventListener("click", () => {
            new Function("scope", "with(scope){ " + callExpr + "; }")(scope);
            render();
          });
        });
        render();
      }

      window.__scopes = {};
      document.querySelectorAll("[ng-app]").forEach((appEl) => {
        const appName = appEl.getAttribute("ng-app");
        const mod = modules[appName];
        const rootScope = {};
        window.__scopes[appName] = { rootScope, controllers: {} };

        const ctrlEls = appEl.hasAttribute("ng-controller")
          ? [appEl]
          : Array.from(appEl.querySelectorAll("[ng-controller]"));

        for (const cEl of ctrlEls) {
          const cname = cEl.getAttribute("ng-controller");
          const childScope = Object.create(rootScope);
          mod._ctrls[cname](childScope, rootScope);
          window.__scopes[appName].controllers[cname] = childScope;
          bindElementTree(cEl, childScope);
        }
      });
    })();
  </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: $scope property rendered without $scope prefix
        actual_1 = {"carname": page.locator("#car-out").text_content()}
        expected_1 = {"carname": "Volvo"}
        cases.append({
            "name": "scope_controller_to_view_binding",
            "expected": expected_1,
            "actual": actual_1,
            "passed": actual_1 == expected_1,
        })

        # Case 2: MVC two-way update + ng-click method
        before_click = page.locator("#mvc-greeting").text_content()
        page.click("#mvc-btn")
        first_click = page.locator("#mvc-greeting").text_content()
        page.fill("#mvc-inp", "Angular")
        page.click("#mvc-btn")
        second_click = page.locator("#mvc-greeting").text_content()
        actual_2 = {
            "before_click": before_click,
            "after_first_click": first_click,
            "after_edit_and_click": second_click,
        }
        expected_2 = {
            "before_click": "",
            "after_first_click": "Hello BlueSky!",
            "after_edit_and_click": "Hello Angular!",
        }
        cases.append({
            "name": "scope_mvc_two_way_and_ng_click",
            "expected": expected_2,
            "actual": actual_2,
            "passed": actual_2 == expected_2,
        })

        # Case 3: ng-repeat creates isolated child scope per item
        repeat_check = page.evaluate("""() => {
            const parent = window.__scopes.app3.controllers.listCtrl;
            const ul = document.getElementById('sec-repeat');
            return {
                items: Array.from(document.querySelectorAll('#repeat-ul li')).map(el => el.textContent),
                child_scope_count: ul.__childScopes.length,
                parent_has_own_x: Object.prototype.hasOwnProperty.call(parent, 'x'),
                child_inherits_parent: ul.__childScopes.every(cs => Object.getPrototypeOf(cs) === parent)
            };
        }""")
        expected_3 = {
            "items": ["Emil", "Tobias", "Linus"],
            "child_scope_count": 3,
            "parent_has_own_x": False,
            "child_inherits_parent": True,
        }
        cases.append({
            "name": "scope_ng_repeat_child_scopes",
            "expected": expected_3,
            "actual": repeat_check,
            "passed": repeat_check == expected_3,
        })

        # Case 4: $rootScope shared across controllers via prototype inheritance
        root_check = page.evaluate("""() => {
            const root = window.__scopes.app4.rootScope;
            const sib = window.__scopes.app4.controllers.siblingCtrl;
            sib.lastname = "LocalOverride";
            return {
                heading: document.getElementById('root-title').textContent,
                family_items: Array.from(document.querySelectorAll('#root-ul li')).map(el => el.textContent),
                sibling_rendered: document.getElementById('sibling-last').textContent,
                sibling_tag: document.getElementById('sibling-shadow').textContent,
                root_unchanged_after_child_shadow: root.lastname === "Refsnes" && sib.lastname === "LocalOverride"
            };
        }""")
        expected_4 = {
            "heading": "Refsnes 家族成员:",
            "family_items": ["Emil Refsnes", "Tobias Refsnes", "Linus Refsnes"],
            "sibling_rendered": "Refsnes",
            "sibling_tag": "inherited:Refsnes",
            "root_unchanged_after_child_shadow": True,
        }
        cases.append({
            "name": "root_scope_shared_across_controllers",
            "expected": expected_4,
            "actual": root_check,
            "passed": root_check == expected_4,
        })

        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-scopes-lab/explore-scopes.py

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

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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