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

AngularJS Bootstrap

核对 AngularJS 结合 Bootstrap 3 样式表构建用户列表与编辑/新建表单的完整示例、指令与 Bootstrap 样式类映射、$watch 校验联动及离线 Chromium 实测。

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

学完这一章,你能够

引入 Bootstrap 样式表与整体页面结构

在 AngularJS 1.x 生态中,Twitter Bootstrap 是最常搭配使用的响应式 CSS 前端框架(系统学习可参考 Bootstrap 专题教程)。在页面 `<head>` 中引入 Bootstrap CSS 即可为表格、按钮与水平表单赋予统一样式;历史教程常列出 MaxCDN 或百度静态资源库的 Bootstrap 3.3.4 外链,但需注意这些早期 HTTP/CDN 节点多已退役或不再受维护,现代部署应改为本地托管静态文件或使用受维护的 HTTPS 镜像及更新版本 Bootstrap。

完整用户管理示例在 `.container` 容器中组合了两大区块:上方是使用 `.table.table-striped` 呈现的 6 名用户列表(每行经 `ng-repeat="user in users"` 渲染,附带调用 `editUser(user.id)` 的编辑按钮与铅笔字形图标),下方是由 `ng-show="edit"` / `ng-hide="edit"` 切换标题的 `.form-horizontal` 水平表单(采用 `.form-group`、`col-sm-2` 标签与 `col-sm-10` 输入区两栏栅格),底部配有受 `ng-disabled="error || incomplete"` 控制的保存按钮。需注意 HTML 示例实际将 `ng-app="myApp"` 与 `ng-controller="userCtrl"` 一并写在 `<body>` 上,而指令说明表中泛称应用入口为 `<html ng-app`。

myUsers.js 控制器、$watch 监控与离线 Chromium 实测

`myUsers.js` 在 `myApp` 模块上注册 `userCtrl` 控制器:初始化 `users`(6 位用户)、姓名与密码字段及 `edit`/`error`/`incomplete` 三个状态标志;`editUser('new')` 切入新建模式(`edit=true`、`incomplete=true` 并清空姓名),而 `editUser(id)` 切入编辑既有用户模式(`edit=false`,回填对应用户的 `fName`/`lName`,同时模板通过 `ng-disabled="!edit"` 锁定既有用户姓名不可改)。控制器通过 `$scope.$watch`(注意速查表原文简写为 `$scope.watch`,实际 API 带 `$` 前缀)监听 `passw1`、`passw2`、`fName`、`lName` 四个模型变化并触发 `$scope.test()`:当两次密码不一致时置 `error=true`,当处于新建模式且任一字段为空时置 `incomplete=true`。

本站离线 Chromium(1024×768 视口,内置 Bootstrap 3.3.4 对应子集样式)实测核验了视觉排版与交互状态机:斑马纹表格渲染 6 行,奇数行背景 `rgb(249, 249, 249)`、偶数行透明,`.btn-success` 背景为 `rgb(92, 184, 92)` 且文字为纯白 `rgb(255, 255, 255)`,`.col-sm-10` 与 `.col-sm-2` 宽度比约 `5:1`;点击第 5 位用户(John Doe)的 Edit 按钮后,`edit` 转为 `false`,`Edit User:` 标题显示而 `Create New User:` 隐藏,姓名框回填 `John` / `Doe` 且均被禁用;点击 `Create New User` 后保存按钮立即禁用,填完姓名与不一致密码(`secret123` vs `secret999`)时 `error=true`、`incomplete=false` 且保存仍禁用,修正为一致密码后 `error=false`、`incomplete=false` 且保存按钮恢复可用。

示例 HTML 中的 AngularJS 指令解析

AngularJS 指令功能描述
<html ng-app>(示例中置于 <body>)定义 AngularJS 应用挂载根节点(示例中命名为 myApp)
<body ng-controller>为页面主体绑定 userCtrl 控制器作用域
<tr ng-repeat>遍历 users 数组,为每个 user 对象生成一行表格记录
<button ng-click>点击编辑或新建按钮时调用 editUser(user.id) 或 editUser('new')
<h3 ng-show>当 edit 为 true(新建模式)时显示 Create New User 标题
<h3 ng-hide>当 edit 为 true 时隐藏 Edit User 标题,edit 为 false 时显示
<input ng-model>将表单输入框双向绑定至 fName、lName、passw1、passw2 模型
<button ng-disabled>当 error(密码不匹配)或 incomplete(必填为空)为 true 时禁用保存按钮

示例使用的 Bootstrap 3 核心样式类解析

HTML 元素Bootstrap 样式类样式定义与作用
<div>container定宽居中响应式页面内容容器
<table>table基础表格排版与单元格内边距样式
<table>table-striped为 tbody 奇数行添加 #f9f9f9 斑马条纹背景
<button>btn按钮基础尺寸、圆角与边框样式
<button>btn-success绿色成功主操作按钮样式(背景 #5cb85c、白字)
<span>glyphiconBootstrap 3 字体图标基类
<span>glyphicon-pencil铅笔编辑图标
<span>glyphicon-user用户新建图标
<span>glyphicon-save保存变更图标
<form>form-horizontal水平排列表单布局,使标签与输入框同行对齐
<div>form-group包裹单组标签与输入控件的间距容器
<label>control-label水平表单右侧对齐标签样式
<label>col-sm-2在 ≥768px 栅格中占据 2/12 列宽(约 16.67%)
<div>col-sm-10在 ≥768px 栅格中占据 10/12 列宽(约 83.33%,与 col-sm-2 呈 5:1)

myUsers.js 中 $scope 属性与方法解析

Scope 成员用途与行为说明
$scope.fName当前表单绑定的用户名字模型变量
$scope.lName当前表单绑定的用户姓氏模型变量
$scope.passw1用户输入的首遍密码模型变量
$scope.passw2用户重复确认的密码模型变量
$scope.users包含 6 条初始用户对象的列表数组
$scope.edit布尔模式标志:新建用户为 true,编辑已有用户为 false
$scope.error当 passw1 !== passw2 时置为 true,触发保存按钮禁用
$scope.incomplete新建模式下任一输入字段长度为 0 时置为 true,触发保存按钮禁用
$scope.editUser(id)按 'new' 或用户 id 切换新建/编辑状态并填充或重置表单字段
$scope.$watch(原文表简写为 $scope.watch)监听 fName、lName、passw1、passw2 变化并回调 $scope.test()
$scope.test()校验两次密码一致性及新建模式字段完整性,更新 error 与 incomplete

离线 Chromium 核验 Bootstrap 3 样式类、用户编辑锁定与 $watch 密码一致性校验

python · 阅读源码
"""Offline Playwright Chromium lab for AngularJS Ch 20: bootstrap."""
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 Bootstrap Lab</title>
<style>
  /* Offline Bootstrap 3.3.4 subset CSS equivalence for tested classes */
  * { box-sizing: border-box; }
  .container { width: 750px; margin-right: auto; margin-left: auto; padding-left: 15px; padding-right: 15px; }
  .table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
  .table th, .table td { padding: 8px; border-top: 1px solid #ddd; text-align: left; }
  .table-striped > tbody > tr:nth-of-type(odd) { background-color: #f9f9f9; }
  .btn { display: inline-block; padding: 6px 12px; border: 1px solid #ccc; border-radius: 4px; background: #fff; cursor: pointer; }
  .btn-success { color: #fff; background-color: #5cb85c; border-color: #4cae4c; }
  .btn:disabled { opacity: 0.65; cursor: not-allowed; }
  .glyphicon { display: inline-block; margin-right: 4px; }
  .form-horizontal .form-group { display: flex; align-items: center; margin-bottom: 12px; }
  .col-sm-2 { width: 16.666667%; padding-right: 10px; }
  .col-sm-10 { width: 83.333333%; }
  .control-label { text-align: right; font-weight: bold; }
  .ng-hide { display: none !important; }
</style>
</head>
<body>
  <div id="root-container" class="container">
    <h3>Users</h3>
    <table id="users-table" class="table table-striped">
      <thead>
        <tr><th>Edit</th><th>First Name</th><th>Last Name</th></tr>
      </thead>
      <tbody id="users-tbody"></tbody>
    </table>
    <hr>
    <button id="btn-create" class="btn btn-success">
      <span class="glyphicon glyphicon-user"></span> Create New User
    </button>
    <hr>
    <h3 id="hdr-create">Create New User:</h3>
    <h3 id="hdr-edit" class="ng-hide">Edit User:</h3>
    <form class="form-horizontal">
      <div class="form-group">
        <label class="col-sm-2 control-label">First Name:</label>
        <div class="col-sm-10">
          <input id="in-fname" type="text" placeholder="First Name">
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">Last Name:</label>
        <div class="col-sm-10">
          <input id="in-lname" type="text" placeholder="Last Name">
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">Password:</label>
        <div class="col-sm-10">
          <input id="in-pass1" type="password" placeholder="Password">
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">Repeat:</label>
        <div class="col-sm-10">
          <input id="in-pass2" type="password" placeholder="Repeat Password">
        </div>
      </div>
    </form>
    <hr>
    <button id="btn-save" class="btn btn-success">
      <span class="glyphicon glyphicon-save"></span> Save Changes
    </button>
  </div>

  <script>
  (function () {
    const scope = {
      fName: "",
      lName: "",
      passw1: "",
      passw2: "",
      users: [
        { id: 1, fName: "Hege", lName: "Pege" },
        { id: 2, fName: "Kim", lName: "Pim" },
        { id: 3, fName: "Sal", lName: "Smith" },
        { id: 4, fName: "Jack", lName: "Jones" },
        { id: 5, fName: "John", lName: "Doe" },
        { id: 6, fName: "Peter", lName: "Pan" }
      ],
      edit: true,
      error: false,
      incomplete: false
    };

    const tbody = document.getElementById("users-tbody");
    const hdrCreate = document.getElementById("hdr-create");
    const hdrEdit = document.getElementById("hdr-edit");
    const inF = document.getElementById("in-fname");
    const inL = document.getElementById("in-lname");
    const inP1 = document.getElementById("in-pass1");
    const inP2 = document.getElementById("in-pass2");
    const btnSave = document.getElementById("btn-save");

    function test() {
      scope.error = scope.passw1 !== scope.passw2;
      scope.incomplete = false;
      if (scope.edit && (!scope.fName.length || !scope.lName.length || !scope.passw1.length || !scope.passw2.length)) {
        scope.incomplete = true;
      }
      render();
    }

    function editUser(id) {
      if (id === "new") {
        scope.edit = true;
        scope.incomplete = true;
        scope.fName = "";
        scope.lName = "";
        scope.passw1 = "";
        scope.passw2 = "";
      } else {
        scope.edit = false;
        scope.fName = scope.users[id - 1].fName;
        scope.lName = scope.users[id - 1].lName;
      }
      test();
    }

    function render() {
      hdrCreate.classList.toggle("ng-hide", !scope.edit);
      hdrEdit.classList.toggle("ng-hide", scope.edit);
      inF.value = scope.fName;
      inL.value = scope.lName;
      inP1.value = scope.passw1;
      inP2.value = scope.passw2;
      inF.disabled = !scope.edit;
      inL.disabled = !scope.edit;
      btnSave.disabled = scope.error || scope.incomplete;
    }

    scope.users.forEach((u) => {
      const tr = document.createElement("tr");
      tr.innerHTML = `
        <td><button class="btn" data-edit-id="${u.id}"><span class="glyphicon glyphicon-pencil"></span> Edit</button></td>
        <td>${u.fName}</td>
        <td>${u.lName}</td>
      `;
      tr.querySelector("button").addEventListener("click", () => editUser(u.id));
      tbody.appendChild(tr);
    });

    document.getElementById("btn-create").addEventListener("click", () => editUser("new"));
    inF.addEventListener("input", () => { scope.fName = inF.value; test(); });
    inL.addEventListener("input", () => { scope.lName = inL.value; test(); });
    inP1.addEventListener("input", () => { scope.passw1 = inP1.value; test(); });
    inP2.addEventListener("input", () => { scope.passw2 = inP2.value; test(); });

    // Initial $watch execution on startup
    test();
    window.__userScope = scope;
  })();
  </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(viewport={"width": 1024, "height": 768})
            page.set_content(HTML_DOC)

            # Case 1: Bootstrap CSS classes rendered on table-striped, btn-success, container, col-sm-2/10
            actual1 = page.evaluate("""() => {
                const rows = document.querySelectorAll("#users-tbody tr");
                const createBtn = document.getElementById("btn-create");
                const lbl = document.querySelector(".col-sm-2.control-label");
                const fieldWrap = document.querySelector(".col-sm-10");
                return {
                    rowCount: rows.length,
                    row0Bg: getComputedStyle(rows[0]).backgroundColor,
                    row1Bg: getComputedStyle(rows[1]).backgroundColor,
                    btnSuccessBg: getComputedStyle(createBtn).backgroundColor,
                    btnSuccessColor: getComputedStyle(createBtn).color,
                    colRatioApprox: Math.round(fieldWrap.getBoundingClientRect().width / lbl.getBoundingClientRect().width)
                };
            }""")
            expected1 = {
                "rowCount": 6,
                "row0Bg": "rgb(249, 249, 249)",
                "row1Bg": "rgba(0, 0, 0, 0)",
                "btnSuccessBg": "rgb(92, 184, 92)",
                "btnSuccessColor": "rgb(255, 255, 255)",
                "colRatioApprox": 5,
            }
            cases.append({"name": "bootstrap_striped_table_button_and_grid_css", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})

            # Case 2: editUser(5) switches to Edit User mode, locks fName/lName, populates John Doe
            page.click("button[data-edit-id='5']")
            actual2 = page.evaluate("""() => ({
                edit: window.__userScope.edit,
                fName: document.getElementById("in-fname").value,
                lName: document.getElementById("in-lname").value,
                fNameDisabled: document.getElementById("in-fname").disabled,
                lNameDisabled: document.getElementById("in-lname").disabled,
                createHdrDisplay: getComputedStyle(document.getElementById("hdr-create")).display,
                editHdrDisplay: getComputedStyle(document.getElementById("hdr-edit")).display,
                saveDisabled: document.getElementById("btn-save").disabled
            })""")
            expected2 = {
                "edit": False,
                "fName": "John",
                "lName": "Doe",
                "fNameDisabled": True,
                "lNameDisabled": True,
                "createHdrDisplay": "none",
                "editHdrDisplay": "block",
                "saveDisabled": False,
            }
            cases.append({"name": "edit_existing_user_mode_and_field_lock", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})

            # Case 3: Create New User mode + $watch password mismatch & completeness gating on Save Changes
            page.click("#btn-create")
            after_new_disabled = page.evaluate("document.getElementById('btn-save').disabled")
            page.fill("#in-fname", "Ada")
            page.fill("#in-lname", "Lovelace")
            page.fill("#in-pass1", "secret123")
            page.fill("#in-pass2", "secret999")
            mismatch = page.evaluate("""() => ({
                error: window.__userScope.error,
                incomplete: window.__userScope.incomplete,
                saveDisabled: document.getElementById("btn-save").disabled
            })""")
            page.fill("#in-pass2", "secret123")
            matched = page.evaluate("""() => ({
                error: window.__userScope.error,
                incomplete: window.__userScope.incomplete,
                saveDisabled: document.getElementById("btn-save").disabled
            })""")
            actual3 = {"after_create_disabled": after_new_disabled, "mismatch": mismatch, "matched": matched}
            expected3 = {
                "after_create_disabled": True,
                "mismatch": {"error": True, "incomplete": False, "saveDisabled": True},
                "matched": {"error": False, "incomplete": False, "saveDisabled": False},
            }
            cases.append({"name": "create_user_watch_password_and_save_gate", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 6 行斑马纹表格、绿色 btn-success、col-sm-10/2 5:1 宽度比、编辑 John Doe 锁定姓名输入框,以及新建模式密码不一致禁用保存、一致后解锁。
离线 Chromium 核验 Bootstrap 3 样式类、用户编辑锁定与 $watch 密码一致性校验

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

当前源码 SHA256:0af902b3d7fdee01e06b967d04d89722c2583329bdb1d4b042ea5eeae3a3bfdd

下载本站示例源码

本地运行

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

下载AngularJS Bootstrap实验

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

ZIP SHA256:af6d844ac2b5e39450113813ed794f7d9235aa1f55e4850a78bd8d1365d34a4e

常见错误与边界

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

练习与解答

在 myUsers.js 示例中,为什么编辑既有用户(edit=false)时姓名输入框会被禁用,且空密码不会让 incomplete 变为 true?

展开参考解答

姓名输入框声明了 ng-disabled="!edit",当 edit=false 时 !edit 为 true 从而锁定姓名字段;同时 test() 中的完整性判断以 if ($scope.edit && (...)) 为前提,因此仅在新建用户模式(edit=true)强制要求四个字段均非空。

规范与官方依据