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

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tables.py
explore-tables.py207 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/angularjs-tables-lab/explore-tables.py

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

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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