蓝色天空.知识 · 实践 · 创造
我的收藏
AngularJS 教程目录 26章
AngularJS / LEARN BY DOING

AngularJS 表单

核对 AngularJS 表单与四类 HTML 输入控件、ng-model 在文本框/复选框/单选框/下拉菜单中的双向绑定行为、novalidate 属性及 angular.copy 重置表单的离线 Chromium 实测。

学完这一章,你能够

  • 核对 AngularJS 表单与四类 HTML 输入控件、ng-model 在文本框/复选框/单选框/下拉菜单中的双向绑定行为、novalidate 属性及 angular.copy 重置表单的离线 Chromium 实测。

HTML 输入控件与 ng-model 数据绑定

AngularJS 表单是一组输入控件的逻辑集合,常见 HTML 控件包括 `input`、`select`、`button` 与 `textarea` 四类元素。

通过为控件添加 `ng-model="firstname"` 指令,可把用户输入与作用域上的 `firstname` 属性建立双向数据绑定:既能在控制器(如 `formCtrl`)中为 `$scope.firstname = "John"` 赋予初值或读取最新输入,也能在页面其他区域用 `{{firstname}}` 实时回显。本站离线 Chromium 实测:初始标题显示 `You entered: John`,在文本框键入 `Alice` 后立即同步为 `You entered: Alice`。

复选框、单选框与下拉菜单的绑定模式

复选框(`<input type="checkbox" ng-model="myVar">`)绑定的模型值为布尔型 `true` 或 `false`,常直接驱动 `ng-show="myVar"` 等显隐条件。本站离线 Chromium 实测:目标标题初始为 `none`,勾选后变为 `block`,取消勾选后恢复 `none`。

一组互斥单选框(`<input type="radio">`)共享同一个 `ng-model="myVar"` 并分别指定不同 `value`(如 `dogs`、`tuts`、`cars`),最终只有当前被选中的那一项的 `value` 会写入 `myVar`。本站实测依次勾选 `tuts` 与 `cars` 后,`myVar` 对应输出 `tuts` 与 `cars`。

原生 `<select ng-model="myVar">` 下拉菜单同样直接将用户所选 `<option>` 的 `value`(如空值、`dogs`、`tuts` 或 `cars`)绑定到 `myVar`。本站离线 Chromium 实测选中 `dogs` 选项后,模型值同步更新为 `dogs`。

完整 HTML 表单、novalidate 与 angular.copy 重置机制

实际业务中通常将多个控件放入 `<form novalidate>` 内统一管理。标准示例中表单包含 `user.firstName` 与 `user.lastName` 两个输入框、一个绑定 `ng-click="reset()"` 的 `RESET` 按钮,并在下方实时对照输出 `form = {{user}}` 与 `master = {{master}}` 两组对象状态。

逐项剖析该应用:`ng-app` 与 `ng-controller` 分别划定应用与 `formCtrl` 控制器边界;两个输入框借由 `ng-model` 绑定到 `user` 对象;控制器中先设定不可变基准对象 `$scope.master = {firstName: "John", lastName: "Doe"}`,再定义 `reset()` 方法调用 `angular.copy($scope.master)` 生成深拷贝赋给 `$scope.user`(并在初始化及点击 `RESET` 按钮时调用),从而确保编辑 `user` 不会反向污染 `master`;`<form>` 上的 HTML5 属性 `novalidate` 虽非语法必需,但在 AngularJS 表单中常用来禁用浏览器原生气泡校验,以便由框架接管统一验证逻辑。本站离线 Chromium 实测:`form.noValidate` 为 `true`;修改姓名为 `Grace Hopper` 后 `user` 变为新值而 `master` 保持 `John Doe` 且两者引用分离(`user !== master`);点击 `RESET` 后 `user` 精准还原为 `{"firstName":"John","lastName":"Doe"}`。

HTML5 novalidate 属性说明

提示主题核心要点
novalidate 属性作用novalidate 是 HTML5 新增表单属性,用于关闭浏览器默认的原生表单校验弹窗,交由 AngularJS 验证指令统一管理校验状态与提示。

离线 Chromium 核验文本框/复选框/单选框/下拉框双向绑定与 angular.copy 表单重置

含完整源码 · 205 行
展开查看收起
python
"""Offline Playwright Chromium lab for AngularJS Ch 17: forms."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS Forms Lab</title>
<style>.ng-hide { display: none !important; }</style>
</head>
<body>
  <section id="sec-text">
    <form>First Name: <input id="in-firstname" type="text"></form>
    <h1 id="out-firstname"></h1>
  </section>

  <section id="sec-checkbox">
    <form><input id="chk-header" type="checkbox"></form>
    <h1 id="chk-target" class="ng-hide">My Header</h1>
  </section>

  <section id="sec-radio">
    <form>
      <input id="rad-dogs" type="radio" name="topic" value="dogs">Dogs
      <input id="rad-tuts" type="radio" name="topic" value="tuts">Tutorials
      <input id="rad-cars" type="radio" name="topic" value="cars">Cars
    </form>
    <div id="out-radio"></div>
  </section>

  <section id="sec-select">
    <form>
      <select id="sel-topic">
        <option value=""></option>
        <option value="dogs">Dogs</option>
        <option value="tuts">Tutorials</option>
        <option value="cars">Cars</option>
      </select>
    </form>
    <div id="out-select"></div>
  </section>

  <section id="sec-form-reset">
    <form id="user-form" novalidate>
      <input id="u-first" type="text">
      <input id="u-last" type="text">
      <button id="btn-reset" type="button">RESET</button>
    </form>
    <p id="out-form-user"></p>
    <p id="out-form-master"></p>
  </section>

  <script>
  (function () {
    function angularCopy(src) {
      return JSON.parse(JSON.stringify(src));
    }

    // 1. text input binding
    const textScope = { firstname: "John" };
    const inFirst = document.getElementById("in-firstname");
    const outFirst = document.getElementById("out-firstname");
    const renderText = () => {
      inFirst.value = textScope.firstname;
      outFirst.textContent = "You entered: " + textScope.firstname;
    };
    inFirst.addEventListener("input", () => { textScope.firstname = inFirst.value; renderText(); });
    renderText();

    // 2. checkbox binding -> ng-show
    const chk = document.getElementById("chk-header");
    const chkTarget = document.getElementById("chk-target");
    chk.addEventListener("change", () => {
      chkTarget.classList.toggle("ng-hide", !chk.checked);
    });

    // 3. radio binding
    const outRadio = document.getElementById("out-radio");
    document.querySelectorAll("input[name='topic']").forEach((r) => {
      r.addEventListener("change", () => {
        if (r.checked) outRadio.textContent = r.value;
      });
    });

    // 4. select binding
    const sel = document.getElementById("sel-topic");
    const outSel = document.getElementById("out-select");
    sel.addEventListener("change", () => { outSel.textContent = sel.value; });

    // 5. form reset with angular.copy(master) & novalidate
    const formScope = {
      master: { firstName: "John", lastName: "Doe" },
      user: null
    };
    const uFirst = document.getElementById("u-first");
    const uLast = document.getElementById("u-last");
    const outUser = document.getElementById("out-form-user");
    const outMaster = document.getElementById("out-form-master");
    function renderForm() {
      uFirst.value = formScope.user.firstName;
      uLast.value = formScope.user.lastName;
      outUser.textContent = "form = " + JSON.stringify(formScope.user);
      outMaster.textContent = "master = " + JSON.stringify(formScope.master);
    }
    function reset() {
      formScope.user = angularCopy(formScope.master);
      renderForm();
    }
    uFirst.addEventListener("input", () => { formScope.user.firstName = uFirst.value; renderForm(); });
    uLast.addEventListener("input", () => { formScope.user.lastName = uLast.value; renderForm(); });
    document.getElementById("btn-reset").addEventListener("click", reset);
    reset();

    window.__formScope = formScope;
  })();
  </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)
        try:
            page = browser.new_page()
            page.set_content(HTML_DOC)

            # Case 1: text input ng-model two-way binding
            init_h1 = page.text_content("#out-firstname")
            page.fill("#in-firstname", "Alice")
            after_h1 = page.text_content("#out-firstname")
            actual1 = {"initial": init_h1, "after_input": after_h1}
            expected1 = {"initial": "You entered: John", "after_input": "You entered: Alice"}
            cases.append({"name": "text_input_ng_model_binding", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})

            # Case 2: checkbox boolean ng-model + ng-show
            before_chk = page.evaluate('getComputedStyle(document.getElementById("chk-target")).display')
            page.check("#chk-header")
            after_chk = page.evaluate('getComputedStyle(document.getElementById("chk-target")).display')
            page.uncheck("#chk-header")
            unchecked = page.evaluate('getComputedStyle(document.getElementById("chk-target")).display')
            actual2 = {"initial": before_chk, "checked": after_chk, "unchecked": unchecked}
            expected2 = {"initial": "none", "checked": "block", "unchecked": "none"}
            cases.append({"name": "checkbox_boolean_ng_show", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})

            # Case 3: radio group and select dropdown ng-model binding
            page.check("#rad-tuts")
            rad_tuts = page.text_content("#out-radio")
            page.check("#rad-cars")
            rad_cars = page.text_content("#out-radio")
            page.select_option("#sel-topic", "dogs")
            sel_dogs = page.text_content("#out-select")
            actual3 = {"radio_1": rad_tuts, "radio_2": rad_cars, "select": sel_dogs}
            expected3 = {"radio_1": "tuts", "radio_2": "cars", "select": "dogs"}
            cases.append({"name": "radio_and_select_ng_model", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})

            # Case 4: complete form novalidate + angular.copy(master) reset isolation
            has_novalidate = page.evaluate('document.getElementById("user-form").noValidate')
            page.fill("#u-first", "Grace")
            page.fill("#u-last", "Hopper")
            edited = {
                "user": page.evaluate("window.__formScope.user"),
                "master": page.evaluate("window.__formScope.master"),
                "distinct_ref": page.evaluate("window.__formScope.user !== window.__formScope.master"),
            }
            page.click("#btn-reset")
            after_reset = {
                "user": page.evaluate("window.__formScope.user"),
                "master": page.evaluate("window.__formScope.master"),
                "dom_user": page.text_content("#out-form-user"),
            }
            actual4 = {"novalidate": has_novalidate, "edited": edited, "after_reset": after_reset}
            expected4 = {
                "novalidate": True,
                "edited": {
                    "user": {"firstName": "Grace", "lastName": "Hopper"},
                    "master": {"firstName": "John", "lastName": "Doe"},
                    "distinct_ref": True,
                },
                "after_reset": {
                    "user": {"firstName": "John", "lastName": "Doe"},
                    "master": {"firstName": "John", "lastName": "Doe"},
                    "dom_user": 'form = {"firstName":"John","lastName":"Doe"}',
                },
            }
            cases.append({"name": "form_novalidate_and_angular_copy_reset", "expected": expected4, "actual": actual4, "passed": actual4 == expected4})
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对文本框同步回显、复选框驱动 ng-show、单选框/下拉框值绑定,以及编辑 user 不污染 master 且点击 RESET 还原初值。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a851.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

JavaScript 对象赋值仅传递引用,若直接写 $scope.user = $scope.master,用户在输入框修改 user.firstName 时会同步改写 master.firstName,导致重置基准丢失;angular.copy() 创建独立深拷贝,保证编辑与基准隔离。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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