蓝色天空网mbsky.com · 知识 · 实践 · 创造AngularJS · 本地阅读预览
教程 / 前端开发 / AngularJS

AngularJS 模型

深入解析 ng-model 指令在 input/select/textarea 控件上的双向绑定、邮箱类型验证、表单字段状态属性($valid/$dirty/$touched/$error)及 9 个动态 CSS 状态类。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

ng-model 与表单控件双向绑定

`ng-model` 指令用于将应用作用域中的模型数据与 HTML 表单控件(`input`、`select`、`textarea`)的值建立双向绑定:控制器赋初始值时控件自动回显,用户在界面修改控件内容时作用域属性也会立即更新,并带动所有依赖该属性的 `{{...}}` 表达式刷新。本站离线 Chromium 实测验证:控制器设置 `$scope.name = "John Doe"` 时输入框与标题均初始化显示 `"John Doe"`,改填 `"Grace Hopper"` 后标题即时更新为 `"你输入了: Grace Hopper"`;对 `<select>`(从 `editor` 切为 `admin`)和 `<textarea>`(改写为 `angular model`)同样实现了实时双向同步。

输入校验与字段状态属性生命周期

配合表单 `name` 与控件 `name`,`ng-model` 可直接对接 HTML5 输入类型校验。以邮箱字段 `<input type="email" name="myAddress" ng-model="emailText">` 为例,当输入不合法邮箱格式时,`myForm.myAddress.$error.email` 会变为 `true`,搭配 `ng-show` 即可动态显隐提示语。本站实测:填入 `"bad-email"` 时提示文本可见,改为合法邮箱 `"dev@example.com"` 后提示自动隐藏。

除 `$error` 外,`ng-model` 还会持续维护 `$valid`/`$invalid`(是否通过所有校验)、`$dirty`/`$pristine`(值是否被修改过)以及 `$touched`/`$untouched`(控件是否曾获得并失去焦点)等应用状态。本站实测对初始值合法且带 `required` 的邮箱框跟踪完整生命周期:初始为 `valid=true, dirty=false, pristine=true, touched=false`;聚焦再失焦后 `touched` 转为 `true` 而 `dirty` 仍为 `false`;改输入非法字符串 `"invalid-mail"` 后转为 `valid=false, dirty=true, pristine=false, touched=true`。

基于状态动态切换的 CSS 类

`ng-model` 会依据字段实时状态自动为宿主控件添加或移除以下 9 个 CSS 类:`ng-empty`(值为空)、`ng-not-empty`(非空)、`ng-touched`(已失焦触碰)、`ng-untouched`(未触碰)、`ng-valid`(校验合法)、`ng-invalid`(校验非法)、`ng-dirty`(已修改)、`ng-pristine`(未修改)以及 `ng-pending`(异步校验挂起中)。借助这些类名,只需编写 `input.ng-invalid { background-color: lightblue; }` 即可纯 CSS 反馈校验状态。本站实测带 `required` 的空输入框初始挂载 `ng-empty`、`ng-invalid`、`ng-pristine`、`ng-untouched` 且计算背景色为 `rgb(173, 216, 230)`(`lightblue`);输入 `"Alice"` 并失焦后类名切换为 `ng-not-empty`、`ng-valid`、`ng-dirty`、`ng-touched`,背景色恢复为 `rgb(255, 255, 255)`。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 input/select/textarea 双向同步;非法邮箱触发 ng-show 显示、合法隐藏;状态从 pristine/untouched 跃迁至 dirty/touched/invalid;空必填框呈现 lightblue 背景并在有效填写后恢复白色。
验证 ng-model 双向绑定、邮箱校验、状态标志跃迁及 ng-invalid 样式切换

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:ba0a964c52ab6a7297ea48bf48481eafcc39863f0defb5155afadbe812c7b675

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载AngularJS 模型实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:663e5b2cda5b5b5e56212156918286034aef427e8ceb8631affc7d9cdc44dd91

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

$dirty 与 $touched 两个表单状态标志分别由什么用户操作触发?为什么 CSS 常将它们与 .ng-invalid 组合使用?

展开参考解答

$dirty 在用户修改控件值后变为 true,而 $touched 在控件获得焦点并失焦(blur)后变为 true。将 .ng-touched.ng-invalid 组合写样式,可以避免页面刚打开尚未填写时就把必填框标红,提升表单体验。

规范与官方依据