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

离线 Chromium 综合实测表达式、过滤器表格、DOM 校验 API 与备忘录 CRUD

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-examples.py
explore-examples.py299 行
"""Offline Playwright Chromium lab for AngularJS Ch 26: examples (comprehensive interactive showcase)."""
import json
from playwright.sync_api import sync_playwright

EXAMPLES_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS 综合实例离线实验</title>
<style>
  .row-even { background-color: rgb(241, 241, 241); }
  .row-odd { background-color: rgb(255, 255, 255); }
  .ng-hide { display: none !important; }
</style>
</head>
<body>
  <!-- 1. Flagship intro ng-model + expression & unbootstrapped comparison -->
  <section id="sec-intro" ng-app="">
    <input id="name-input" type="text">
    <h1 id="hello-out">Hello </h1>
    <p id="expr-calc"></p>
  </section>
  <section id="sec-no-app">
    <p id="raw-expr">{{ 5 + 5 }}</p>
  </section>

  <!-- 2. Filters + sorted zebra table -->
  <section id="sec-table">
    <input id="filter-input" type="text">
    <table id="data-tbl"><tbody></tbody></table>
    <p id="filter-summary"></p>
  </section>

  <!-- 3. DOM, Events, Form validation, Core APIs -->
  <section id="sec-dom">
    <input id="chk-disable" type="checkbox">
    <button id="btn-target">提交</button>
    <button id="btn-toggle">切换显示</button>
    <div id="toggle-panel">可见面板</div>
    <input id="email-input" type="email" required>
    <span id="email-state"></span>
  </section>

  <!-- 4. Todo / Memo app -->
  <section id="sec-todo">
    <input id="todo-input" type="text">
    <button id="todo-add">新增</button>
    <button id="todo-remove">删除已勾选</button>
    <ul id="todo-list"></ul>
  </section>

  <script>
    // 1. Intro binding & expression evaluation
    const nameInput = document.getElementById('name-input');
    const helloOut = document.getElementById('hello-out');
    nameInput.addEventListener('input', () => {
      helloOut.textContent = 'Hello ' + nameInput.value;
    });
    const person = { first: 'John', last: 'Doe' };
    const scores = [10, 20, 30];
    document.getElementById('expr-calc').textContent =
      (5 + 5) + '|' + (person.first + ' ' + person.last) + '|' + scores[2];

    // 2. Filters (uppercase, lowercase, currency, orderBy, filter) + table ($index, $even, $odd)
    const records = [
      { Name: 'Alfreds', Country: 'Germany', Price: 19.5 },
      { Name: 'Centro', Country: 'Mexico', Price: 8.2 },
      { Name: 'Ernst', Country: 'Austria', Price: 42.0 }
    ];
    function renderTable(query) {
      const q = (query || '').toLowerCase();
      const filtered = records
        .filter(r => !q || r.Name.toLowerCase().includes(q) || r.Country.toLowerCase().includes(q))
        .slice()
        .sort((a, b) => a.Country.localeCompare(b.Country));
      const tbody = document.querySelector('#data-tbl tbody');
      tbody.innerHTML = '';
      filtered.forEach((item, idx) => {
        const tr = document.createElement('tr');
        tr.className = idx % 2 === 0 ? 'row-even' : 'row-odd';
        tr.innerHTML =
          '<td>' + (idx + 1) + '</td>' +
          '<td>' + item.Name + '</td>' +
          '<td>' + item.Country.toUpperCase() + '</td>' +
          '<td>$' + item.Price.toFixed(2) + '</td>';
        tbody.appendChild(tr);
      });
    }
    renderTable('');
    document.getElementById('filter-input').addEventListener('input', (e) => renderTable(e.target.value));
    document.getElementById('filter-summary').textContent =
      'JOHN'.toLowerCase() + '|' + 'john'.toUpperCase() + '|$' + (12.5).toFixed(2);

    // 3. DOM (ng-disabled, ng-show/ng-hide), Events (ng-click), Form validation & AngularJS utility APIs
    const chkDisable = document.getElementById('chk-disable');
    const btnTarget = document.getElementById('btn-target');
    chkDisable.addEventListener('change', () => { btnTarget.disabled = chkDisable.checked; });

    const btnToggle = document.getElementById('btn-toggle');
    const togglePanel = document.getElementById('toggle-panel');
    let clicks = 0;
    btnToggle.addEventListener('click', () => {
      clicks += 1;
      togglePanel.classList.toggle('ng-hide');
    });

    const emailInput = document.getElementById('email-input');
    const emailState = document.getElementById('email-state');
    let emailDirty = false;
    function updateEmailState() {
      const valid = emailInput.checkValidity();
      emailState.textContent = (emailDirty ? 'dirty' : 'pristine') + ':' + (valid ? 'valid' : 'invalid');
    }
    emailInput.addEventListener('input', () => { emailDirty = true; updateEmailState(); });
    updateEmailState();

    window.angularApi = {
      lowercase: (s) => (typeof s === 'string' ? s.toLowerCase() : s),
      uppercase: (s) => (typeof s === 'string' ? s.toUpperCase() : s),
      isString: (v) => typeof v === 'string',
      isNumber: (v) => typeof v === 'number',
      getClicks: () => clicks
    };

    // 4. Todo / Memo app (备忘录应用)
    let todos = [
      { text: '学习 AngularJS 指令', done: true },
      { text: '编写过滤器表格', done: false }
    ];
    function renderTodos() {
      const ul = document.getElementById('todo-list');
      ul.innerHTML = '';
      todos.forEach((t, i) => {
        const li = document.createElement('li');
        li.innerHTML = '<input type="checkbox" data-idx="' + i + '"' + (t.done ? ' checked' : '') + '><span>' + t.text + '</span>';
        li.querySelector('input').addEventListener('change', (ev) => {
          todos[i].done = ev.target.checked;
        });
        ul.appendChild(li);
      });
    }
    renderTodos();
    document.getElementById('todo-add').addEventListener('click', () => {
      const val = document.getElementById('todo-input').value.trim();
      if (!val) return;
      todos.push({ text: val, done: false });
      document.getElementById('todo-input').value = '';
      renderTodos();
    });
    document.getElementById('todo-remove').addEventListener('click', () => {
      todos = todos.filter(t => !t.done);
      renderTodos();
    });
  </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(EXAMPLES_HTML, wait_until="load")

            # Case 1: Intro binding + expressions vs unbootstrapped container
            page.fill("#name-input", "BlueSky")
            res1 = {
                "hello_heading": page.locator("#hello-out").inner_text(),
                "expr_summary": page.locator("#expr-calc").inner_text(),
                "without_ng_app": page.locator("#raw-expr").inner_text(),
            }
            exp1 = {
                "hello_heading": "Hello BlueSky",
                "expr_summary": "10|John Doe|30",
                "without_ng_app": "{{ 5 + 5 }}",
            }
            cases.append(dict(
                name="intro_binding_and_expressions",
                expected=exp1,
                actual=res1,
                passed=(res1 == exp1),
            ))

            # Case 2: Filters (uppercase/lowercase/currency/orderBy/filter) & zebra table ($index, $even, $odd)
            all_rows = page.evaluate("""() => Array.from(document.querySelectorAll('#data-tbl tbody tr')).map(tr => ({
                cls: tr.className,
                bg: getComputedStyle(tr).backgroundColor,
                cells: Array.from(tr.querySelectorAll('td')).map(td => td.textContent)
            }))""")
            page.fill("#filter-input", "ger")
            filtered_rows = page.evaluate("""() => Array.from(document.querySelectorAll('#data-tbl tbody tr')).map(tr =>
                Array.from(tr.querySelectorAll('td')).map(td => td.textContent)
            )""")
            res2 = {
                "sorted_first_row_country": all_rows[0]["cells"][2],
                "zebra_classes": [r["cls"] for r in all_rows],
                "even_bg": all_rows[0]["bg"],
                "odd_bg": all_rows[1]["bg"],
                "filtered_rows": filtered_rows,
                "filter_summary": page.locator("#filter-summary").inner_text(),
            }
            exp2 = {
                "sorted_first_row_country": "AUSTRIA",
                "zebra_classes": ["row-even", "row-odd", "row-even"],
                "even_bg": "rgb(241, 241, 241)",
                "odd_bg": "rgb(255, 255, 255)",
                "filtered_rows": [["1", "Alfreds", "GERMANY", "$19.50"]],
                "filter_summary": "john|JOHN|$12.50",
            }
            cases.append(dict(
                name="directives_filters_and_sorted_table",
                expected=exp2,
                actual=res2,
                passed=(res2 == exp2),
            ))

            # Case 3: DOM (ng-disabled/ng-hide), Events (ng-click), Form validation & AngularJS API utilities
            page.check("#chk-disable")
            btn_disabled = page.locator("#btn-target").is_disabled()
            page.click("#btn-toggle")
            panel_hidden = page.locator("#toggle-panel").is_hidden()
            page.fill("#email-input", "bad-email")
            invalid_state = page.locator("#email-state").inner_text()
            page.fill("#email-input", "dev@example.com")
            valid_state = page.locator("#email-state").inner_text()
            api_check = page.evaluate("""() => ({
                lower: window.angularApi.lowercase('AngularJS'),
                upper: window.angularApi.uppercase('AngularJS'),
                isStr: window.angularApi.isString('abc'),
                isNum: window.angularApi.isNumber(42),
                clicks: window.angularApi.getClicks()
            })""")
            res3 = {
                "btn_disabled": btn_disabled,
                "panel_hidden": panel_hidden,
                "invalid_state": invalid_state,
                "valid_state": valid_state,
                **api_check,
            }
            exp3 = {
                "btn_disabled": True,
                "panel_hidden": True,
                "invalid_state": "dirty:invalid",
                "valid_state": "dirty:valid",
                "lower": "angularjs",
                "upper": "ANGULARJS",
                "isStr": True,
                "isNum": True,
                "clicks": 1,
            }
            cases.append(dict(
                name="dom_events_forms_and_validation",
                expected=exp3,
                actual=res3,
                passed=(res3 == exp3),
            ))

            # Case 4: Todo / Memo application CRUD (add + remove completed)
            init_count = page.locator("#todo-list li").count()
            page.fill("#todo-input", "复习路由配置")
            page.click("#todo-add")
            after_add_count = page.locator("#todo-list li").count()
            page.click("#todo-remove")
            remaining_texts = page.locator("#todo-list li span").all_inner_texts()
            res4 = {
                "initial_count": init_count,
                "after_add_count": after_add_count,
                "after_remove_done": remaining_texts,
            }
            exp4 = {
                "initial_count": 2,
                "after_add_count": 3,
                "after_remove_done": ["编写过滤器表格", "复习路由配置"],
            }
            cases.append(dict(
                name="todo_memo_application_crud",
                expected=exp4,
                actual=res4,
                passed=(res4 == exp4),
            ))
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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