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

验证 ng-model 双向绑定、邮箱校验、状态标志跃迁及 ng-invalid 样式切换

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-model.py
explore-model.py300 行
"""Offline Playwright Chromium lab for AngularJS Ch 05 (model)."""
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 ng-model Offline Lab</title>
<style>
  input { background-color: rgb(255, 255, 255); }
  input.ng-invalid { background-color: lightblue; }
</style>
</head>
<body>
  <div id="sec-basic" ng-app="myApp" ng-controller="myCtrl">
    <input id="basic-inp" ng-model="name">
    <h1 id="basic-out">你输入了: {{name}}</h1>
  </div>

  <form id="sec-email" ng-app="" name="emailForm">
    <input id="email-inp" type="email" name="myAddress" ng-model="emailText">
    <span id="email-warn" ng-show="emailForm.myAddress.$error.email">不是一个合法的邮箱地址</span>
  </form>

  <form id="sec-status" ng-app="" name="statusForm" ng-init="myText='dev@example.com'">
    <input id="status-inp" type="email" name="myAddress" ng-model="myText" required>
    <p id="st-valid">{{statusForm.myAddress.$valid}}</p>
    <p id="st-dirty">{{statusForm.myAddress.$dirty}}</p>
    <p id="st-pristine">{{statusForm.myAddress.$pristine}}</p>
    <p id="st-touched">{{statusForm.myAddress.$touched}}</p>
  </form>

  <form id="sec-css" ng-app="" name="cssForm">
    <input id="css-inp" name="myName" ng-model="userName" required>
  </form>

  <div id="sec-controls" ng-app="" ng-init="role='editor';bio='hello'">
    <select id="ctrl-select" ng-model="role">
      <option value="viewer">Viewer</option>
      <option value="editor">Editor</option>
      <option value="admin">Admin</option>
    </select>
    <textarea id="ctrl-ta" ng-model="bio"></textarea>
    <p id="ctrl-summary">{{role}} | {{bio}}</p>
  </div>

  <script>
    (function () {
      const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      const ctrls = {
        myCtrl($scope) {
          $scope.name = "John Doe";
        }
      };

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

      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);
        }
        const ctrlName = root.getAttribute("ng-controller");
        if (ctrlName && ctrls[ctrlName]) ctrls[ctrlName](scope);

        const formName = root.tagName === "FORM" ? root.getAttribute("name") : null;
        if (formName) scope[formName] = {};

        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 showEls = Array.from(root.querySelectorAll("[ng-show]"));

        function render() {
          for (const b of textBindings) {
            b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => {
              const v = evalExpr(ex.trim(), scope);
              return v === undefined || v === null ? "" : String(v);
            });
          }
          for (const el of showEls) {
            const ok = Boolean(evalExpr(el.getAttribute("ng-show"), scope));
            el.style.display = ok ? "" : "none";
          }
        }

        function attachModel(el) {
          const prop = el.getAttribute("ng-model");
          if (scope[prop] !== undefined) el.value = scope[prop];
          else scope[prop] = el.value || "";

          const state = {
            $pristine: true,
            $dirty: false,
            $untouched: true,
            $touched: false,
            $valid: true,
            $invalid: false,
            $error: {}
          };
          const fieldName = el.getAttribute("name");
          if (formName && fieldName) scope[formName][fieldName] = state;

          function syncState() {
            const val = el.value;
            const isEmpty = val.length === 0;
            const errs = {};
            if (el.hasAttribute("required") && isEmpty) errs.required = true;
            if (el.getAttribute("type") === "email" && !isEmpty && !EMAIL_RE.test(val)) {
              errs.email = true;
            }
            state.$error = errs;
            state.$invalid = Object.keys(errs).length > 0;
            state.$valid = !state.$invalid;

            el.classList.toggle("ng-empty", isEmpty);
            el.classList.toggle("ng-not-empty", !isEmpty);
            el.classList.toggle("ng-pristine", state.$pristine);
            el.classList.toggle("ng-dirty", state.$dirty);
            el.classList.toggle("ng-untouched", state.$untouched);
            el.classList.toggle("ng-touched", state.$touched);
            el.classList.toggle("ng-valid", state.$valid);
            el.classList.toggle("ng-invalid", state.$invalid);
          }

          const evt = el.tagName === "SELECT" ? "change" : "input";
          el.addEventListener(evt, () => {
            state.$pristine = false;
            state.$dirty = true;
            scope[prop] = el.value;
            syncState();
            render();
          });
          el.addEventListener("blur", () => {
            state.$untouched = false;
            state.$touched = true;
            syncState();
            render();
          });
          syncState();
        }

        root.querySelectorAll("[ng-model]").forEach(attachModel);
        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: controller init & two-way binding
        init_val = page.locator("#basic-inp").input_value()
        init_out = page.locator("#basic-out").text_content()
        page.fill("#basic-inp", "Grace Hopper")
        upd_out = page.locator("#basic-out").text_content()
        actual_1 = {
            "init_input": init_val,
            "init_heading": init_out,
            "updated_heading": upd_out,
        }
        expected_1 = {
            "init_input": "John Doe",
            "init_heading": "你输入了: John Doe",
            "updated_heading": "你输入了: Grace Hopper",
        }
        cases.append({
            "name": "ng_model_init_and_two_way_binding",
            "expected": expected_1,
            "actual": actual_1,
            "passed": actual_1 == expected_1,
        })

        # Case 2: email validation + ng-show
        page.fill("#email-inp", "bad-email")
        bad_visible = page.locator("#email-warn").is_visible()
        page.fill("#email-inp", "dev@example.com")
        good_visible = page.locator("#email-warn").is_visible()
        actual_2 = {"invalid_shows_warn": bad_visible, "valid_hides_warn": not good_visible}
        expected_2 = {"invalid_shows_warn": True, "valid_hides_warn": True}
        cases.append({
            "name": "ng_model_email_validation_ng_show",
            "expected": expected_2,
            "actual": actual_2,
            "passed": actual_2 == expected_2,
        })

        # Case 3: $valid / $dirty / $pristine / $touched lifecycle
        def read_status():
            return {
                "valid": page.locator("#st-valid").text_content(),
                "dirty": page.locator("#st-dirty").text_content(),
                "pristine": page.locator("#st-pristine").text_content(),
                "touched": page.locator("#st-touched").text_content(),
            }
        st_init = read_status()
        page.locator("#status-inp").focus()
        page.locator("#status-inp").blur()
        st_blurred = read_status()
        page.fill("#status-inp", "invalid-mail")
        st_invalid = read_status()
        actual_3 = {"init": st_init, "after_blur": st_blurred, "after_invalid_edit": st_invalid}
        expected_3 = {
            "init": {"valid": "true", "dirty": "false", "pristine": "true", "touched": "false"},
            "after_blur": {"valid": "true", "dirty": "false", "pristine": "true", "touched": "true"},
            "after_invalid_edit": {"valid": "false", "dirty": "true", "pristine": "false", "touched": "true"},
        }
        cases.append({
            "name": "ng_model_status_flags_lifecycle",
            "expected": expected_3,
            "actual": actual_3,
            "passed": actual_3 == expected_3,
        })

        # Case 4: ng-* CSS classes & input.ng-invalid lightblue style
        before_cls = page.evaluate("""() => {
            const el = document.getElementById('css-inp');
            return {
                classes: Array.from(el.classList).sort(),
                bg: getComputedStyle(el).backgroundColor
            };
        }""")
        page.fill("#css-inp", "Alice")
        page.locator("#css-inp").blur()
        after_cls = page.evaluate("""() => {
            const el = document.getElementById('css-inp');
            return {
                classes: Array.from(el.classList).sort(),
                bg: getComputedStyle(el).backgroundColor
            };
        }""")
        actual_4 = {"empty_invalid": before_cls, "filled_valid": after_cls}
        expected_4 = {
            "empty_invalid": {
                "classes": ["ng-empty", "ng-invalid", "ng-pristine", "ng-untouched"],
                "bg": "rgb(173, 216, 230)",
            },
            "filled_valid": {
                "classes": ["ng-dirty", "ng-not-empty", "ng-touched", "ng-valid"],
                "bg": "rgb(255, 255, 255)",
            },
        }
        cases.append({
            "name": "ng_model_css_classes_and_style",
            "expected": expected_4,
            "actual": actual_4,
            "passed": actual_4 == expected_4,
        })

        # Case 5: select & textarea controls bound via ng-model
        init_ctrl = page.locator("#ctrl-summary").text_content()
        page.select_option("#ctrl-select", "admin")
        page.fill("#ctrl-ta", "angular model")
        upd_ctrl = page.locator("#ctrl-summary").text_content()
        actual_5 = {"initial": init_ctrl, "updated": upd_ctrl}
        expected_5 = {"initial": "editor | hello", "updated": "admin | angular model"}
        cases.append({
            "name": "ng_model_select_and_textarea_controls",
            "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-model-lab/explore-model.py

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

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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