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

AngularJS 表格

核对 AngularJS 结合 ng-repeat 与 $http 渲染数据表格、v1.5+ .then 替代废弃 .success/.error、CSS 隔行样式、orderBy/uppercase 过滤器及 $index/$even/$odd 用法。

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

学完这一章,你能够

使用 ng-repeat 与 $http 在表格中渲染数据

`ng-repeat` 指令非常适合将结构化数组渲染为 HTML 表格:在 `<tr>` 上声明 `ng-repeat="x in names"` 并在 `<td>` 内插值 `{{ x.Name }}` 与 `{{ x.Country }}`,即可按记录条数自动展开全部数据行。控制器通过 `$http.get(...)` 拉取服务端返回的 JSON 数据并把 `records` 数组赋给 `$scope.names`。

版本迁移方面需注意:自 AngularJS v1.5 起,`$http` 的 `.success()` 与 `.error()` 方法已被废弃(v1.6 起彻底移除),官方统一改用标准 Promise 风格的 `.then(function (result) { $scope.names = result.data.records; })`,其中响应体位于 `result.data` 下;而 v1.5 以下旧代码则使用 `.success(function (response) { $scope.names = response.records; })`。后端示例 `Customers_JSON.php` 输出顶层键为 `records`、元素含 `Name`/`City`/`Country` 的标准 JSON 列表。本站离线 Chromium 实测两种回调路径均解析出 6 条客户记录,首行为 `Alfreds Futterkiste / Germany`,末行为 `Cactus Comidas para llevar / Argentina`。

表格 CSS 美化与 orderBy / uppercase 过滤器

为提升表格可读性,可在页面 `<style>` 中为 `table, th, td` 设置 `1px solid grey` 边框、`border-collapse: collapse` 合并边框及 `5px` 内边距,并借助 CSS 伪类 `table tr:nth-child(odd)`(`#f1f1f1`)与 `table tr:nth-child(even)`(`#ffffff`)实现斑马纹。本站 Chromium 实测计算样式确认 `borderCollapse` 为 `collapse`、单元格 `padding` 为 `5px`,首行与次行背景色分别为 `rgb(241, 241, 241)` 与 `rgb(255, 255, 255)`。

表格展示可直接叠加内置过滤器:在循环表达式中写作 `ng-repeat="x in names | orderBy : 'Country'"` 可按国家字段字母升序重排数据行;在单元格插值中写作 `{{ x.Country | uppercase }}` 可将国家名称转为全大写。本站离线实测 `orderBy : 'Country'` 排序序列为 `["Argentina", "Canada", "Germany", "Mexico", "Sweden", "UK"]`,`uppercase` 过滤后前 3 行国家输出为 `["GERMANY", "MEXICO", "UK"]`。

行序号 $index 与奇偶标志 $even / $odd

`ng-repeat` 为每一行自动暴露从 `0` 开始的局部序号变量 `$index`,在首列单元格写入 `{{ $index + 1 }}` 即可呈现符合阅读习惯的 1 起始递增序号。本站实测 6 行客户表格首列依次输出 `["1", "2", "3", "4", "5", "6"]`。

除了纯 CSS 伪类,也可利用 `ng-repeat` 内置布尔变量 `$odd` 与 `$even` 配合 `ng-if` 控制单元格背景色(例如在 `ng-if="$odd"` 分支设置 `style="background-color:#f1f1f1"`)。需留意 `$index` 从 `0` 计数,因此第 1 行(索引 0)对应 `$even = true`、第 2 行(索引 1)对应 `$odd = true`,与 1 起始的 CSS `:nth-child(odd)` 恰好相反。本站实测前 4 行单元格背景色依次为透明、`rgb(241, 241, 241)`、透明、`rgb(241, 241, 241)`。

离线 Chromium 核验 ng-repeat 表格渲染、CSS 斑马纹、orderBy/uppercase 与 $index/$odd/$even

python · 阅读源码
"""Offline Playwright Chromium lab for AngularJS Ch 12: tables."""
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 Tables Lab</title>
<style>
  #tbl-css, #tbl-css th, #tbl-css td {
    border: 1px solid grey;
    border-collapse: collapse;
    padding: 5px;
  }
  #tbl-css tr:nth-child(odd) { background-color: #f1f1f1; }
  #tbl-css tr:nth-child(even) { background-color: #ffffff; }
</style>
</head>
<body>
  <table id="tbl-basic"></table>
  <table id="tbl-css"></table>
  <table id="tbl-orderby"></table>
  <table id="tbl-uppercase"></table>
  <table id="tbl-index"></table>
  <table id="tbl-odd-even"></table>

  <script>
  (function () {
    const payload = {
      records: [
        { Name: "Alfreds Futterkiste", City: "Berlin", Country: "Germany" },
        { Name: "Ana Trujillo Emparedados y helados", City: "México D.F.", Country: "Mexico" },
        { Name: "Around the Horn", City: "London", Country: "UK" },
        { Name: "Berglunds snabbköp", City: "Luleå", Country: "Sweden" },
        { Name: "Bottom-Dollar Marketse", City: "Tsawassen", Country: "Canada" },
        { Name: "Cactus Comidas para llevar", City: "Buenos Aires", Country: "Argentina" }
      ]
    };

    // Offline equivalence of $http.get().then(result => result.data.records)
    // vs legacy <1.5 .success(response => response.records)
    function mockHttpGet() {
      const p = Promise.resolve({ status: 200, data: payload });
      p.success = (fn) => p.then((res) => fn(res.data));
      return p;
    }

    window.__labReady = (async () => {
      let namesThen = [];
      let namesLegacy = [];
      await mockHttpGet().then((result) => { namesThen = result.data.records; });
      await mockHttpGet().success((response) => { namesLegacy = response.records; });

      // 1. Basic ng-repeat table
      const tblBasic = document.getElementById("tbl-basic");
      namesThen.forEach((x) => {
        const tr = document.createElement("tr");
        tr.innerHTML = `<td>${x.Name}</td><td>${x.Country}</td>`;
        tblBasic.appendChild(tr);
      });

      // 2. CSS striped table
      const tblCss = document.getElementById("tbl-css");
      namesThen.forEach((x) => {
        const tr = document.createElement("tr");
        tr.innerHTML = `<td>${x.Name}</td><td>${x.Country}</td>`;
        tblCss.appendChild(tr);
      });

      // 3. orderBy : 'Country'
      const tblOrder = document.getElementById("tbl-orderby");
      const sorted = [...namesThen].sort((a, b) => a.Country.localeCompare(b.Country, "en"));
      sorted.forEach((x) => {
        const tr = document.createElement("tr");
        tr.innerHTML = `<td>${x.Name}</td><td>${x.Country}</td>`;
        tblOrder.appendChild(tr);
      });

      // 4. uppercase filter on Country
      const tblUpper = document.getElementById("tbl-uppercase");
      namesThen.forEach((x) => {
        const tr = document.createElement("tr");
        tr.innerHTML = `<td>${x.Name}</td><td>${x.Country.toUpperCase()}</td>`;
        tblUpper.appendChild(tr);
      });

      // 5. $index + 1
      const tblIndex = document.getElementById("tbl-index");
      namesThen.forEach((x, idx) => {
        const tr = document.createElement("tr");
        tr.innerHTML = `<td>${idx + 1}</td><td>${x.Name}</td><td>${x.Country}</td>`;
        tblIndex.appendChild(tr);
      });

      // 6. $odd and $even (0-based AngularJS semantics: idx=0 => $even, idx=1 => $odd)
      const tblOE = document.getElementById("tbl-odd-even");
      namesThen.forEach((x, idx) => {
        const tr = document.createElement("tr");
        const isOdd = idx % 2 === 1;
        const styleAttr = isOdd ? ' style="background-color:#f1f1f1"' : "";
        tr.innerHTML = `<td${styleAttr}>${x.Name}</td><td${styleAttr}>${x.Country}</td>`;
        tblOE.appendChild(tr);
      });

      return { thenCount: namesThen.length, legacyCount: namesLegacy.length };
    })();
  })();
  </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)
            http_counts = page.evaluate("window.__labReady")

            # Case 1: ng-repeat basic render & $http .then vs deprecated .success
            basic_rows = page.eval_on_selector_all(
                "#tbl-basic tr",
                "rows => rows.map(r => Array.from(r.querySelectorAll('td')).map(td => td.textContent))"
            )
            actual1 = {
                "then_count": http_counts["thenCount"],
                "legacy_count": http_counts["legacyCount"],
                "row_count": len(basic_rows),
                "first_row": basic_rows[0],
                "last_row": basic_rows[-1],
            }
            expected1 = {
                "then_count": 6,
                "legacy_count": 6,
                "row_count": 6,
                "first_row": ["Alfreds Futterkiste", "Germany"],
                "last_row": ["Cactus Comidas para llevar", "Argentina"],
            }
            cases.append({"name": "ng_repeat_table_and_http_then_compat", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})

            # Case 2: CSS styling (border-collapse, padding, nth-child odd/even background)
            actual2 = page.evaluate("""() => {
                const tbl = document.getElementById("tbl-css");
                const rows = tbl.querySelectorAll("tr");
                const td = rows[0].querySelector("td");
                return {
                    borderCollapse: getComputedStyle(tbl).borderCollapse,
                    tdPadding: getComputedStyle(td).padding,
                    row0Bg: getComputedStyle(rows[0]).backgroundColor,
                    row1Bg: getComputedStyle(rows[1]).backgroundColor
                };
            }""")
            expected2 = {
                "borderCollapse": "collapse",
                "tdPadding": "5px",
                "row0Bg": "rgb(241, 241, 241)",
                "row1Bg": "rgb(255, 255, 255)",
            }
            cases.append({"name": "table_css_collapse_and_nth_child", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})

            # Case 3: orderBy 'Country' and uppercase filter
            ordered_countries = page.eval_on_selector_all("#tbl-orderby tr td:nth-child(2)", "els => els.map(e => e.textContent)")
            upper_countries = page.eval_on_selector_all("#tbl-uppercase tr td:nth-child(2)", "els => els.map(e => e.textContent)")
            actual3 = {"ordered_countries": ordered_countries, "upper_first_three": upper_countries[:3]}
            expected3 = {
                "ordered_countries": ["Argentina", "Canada", "Germany", "Mexico", "Sweden", "UK"],
                "upper_first_three": ["GERMANY", "MEXICO", "UK"],
            }
            cases.append({"name": "orderby_country_and_uppercase_filter", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})

            # Case 4: $index + 1 numbering and 0-based $odd / $even inline shading
            indices = page.eval_on_selector_all("#tbl-index tr td:first-child", "els => els.map(e => e.textContent)")
            odd_even_bgs = page.evaluate("""() => {
                const rows = document.querySelectorAll("#tbl-odd-even tr");
                return [0, 1, 2, 3].map(i => getComputedStyle(rows[i].querySelector("td")).backgroundColor);
            }""")
            actual4 = {"indices": indices, "td_bg_first_four": odd_even_bgs}
            expected4 = {
                "indices": ["1", "2", "3", "4", "5", "6"],
                "td_bg_first_four": [
                    "rgba(0, 0, 0, 0)",
                    "rgb(241, 241, 241)",
                    "rgba(0, 0, 0, 0)",
                    "rgb(241, 241, 241)",
                ],
            }
            cases.append({"name": "index_numbering_and_odd_even_shading", "expected": expected4, "actual": actual4, "passed": actual4 == expected4})
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 6 行表格渲染、collapse/5px/nth-child 背景色、按 Country 升序排列、大写转换、1-6 序号及 0 起始 $odd 浅灰着色。
离线 Chromium 核验 ng-repeat 表格渲染、CSS 斑马纹、orderBy/uppercase 与 $index/$odd/$even

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

当前源码 SHA256:f3b72d0dfc4eee6cb4481f1c77630e0e03b2a87293b5a2116e0056a1e0eea723

下载本站示例源码

本地运行

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

下载AngularJS 表格实验

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

ZIP SHA256:4577e8c1fe298302ad3324b16c379de490d497dc68b2bd50d84df193d2105051

常见错误与边界

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

练习与解答

AngularJS 1.5+ 用 .then() 替代 .success() 获取 $http 数据时,读取 JSON 载荷的写法有什么变化?为什么 $odd 斑马纹与 CSS :nth-child(odd) 的着色行不同?

展开参考解答

.then(result) 传入的是包含 status、headers 与 data 的完整响应对象,因此需访问 result.data.records,而旧版 .success(response) 直接接收解包后的响应体;$odd/$even 按 0 起始的 $index 判断(索引 1 即第 2 行为 $odd),而 CSS :nth-child(odd) 按 1 起始序号匹配(第 1 行为 odd)。

规范与官方依据