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

AngularJS Select

核对 AngularJS 使用 ng-options 与 ng-repeat 构建下拉选择框的机制差异、数组与键值对对象数据源绑定行为及离线 Chromium 实测结果。

学完这一章,你能够

  • 核对 AngularJS 使用 ng-options 与 ng-repeat 构建下拉选择框的机制差异、数组与键值对对象数据源绑定行为及离线 Chromium 实测结果。

使用 ng-options 与 ng-init 构建数组下拉框

AngularJS 支持直接基于数组或对象数据源动态渲染 `<select>` 下拉列表。推荐采用 `ng-options` 指令(配合 `ng-model` 绑定当前选中值)遍历数据源,例如 `ng-options="x for x in names"` 会把数组元素逐一生成为下拉选项;在 `<select>` 上结合 `ng-init="selectedName = names[0]"` 即可指定初始默认选中项,避免列表初次加载时出现空白占位行。本站离线 Chromium 实测 3 项数组 `["Google", "BlueSky", "Taobao"]`:初始绑定值自动落在 `Google`,切换至第 3 项后视图同步更新为 `Taobao`。

ng-options 与 ng-repeat 的对象/字符串绑定差异

开发者虽然也能借助 `<option ng-repeat="x in names">{{x}}</option>` 循环拼装选项,但 `ng-repeat` 本质是按字符串复制 DOM 节点,绑定的选中值只能是纯字符串;而 `ng-options` 专为选择框设计,可以直接将整个 JavaScript 对象作为选中值写入 `ng-model`。

面对包含名称与网址的对象数组 `sites`(每项含 `site` 与 `url` 字段),这种差异尤为明显:使用 `ng-repeat` 并设置 `value="{{x.url}}"` 时,选中后 `selectedSite` 仅保存单个字符串(本站实测选中第二项后 `typeof` 为 `string`,值为 `https://example.org/bluesky`,标题显示 `你选择的是: https://example.org/bluesky`);改用 `ng-options="x.site for x in sites"` 后,`selectedSite` 直接持有完整对象(`typeof` 为 `object`),模板可同时读取 `{{selectedSite.site}}`(`BlueSky`)与 `{{selectedSite.url}}`(`https://example.org/bluesky`),业务扩展更加灵活。

使用键值对对象及嵌套对象作为数据源

当数据源从数组改为键值对对象(如 `{site01: "Google", site02: "BlueSky", site03: "Taobao"}`)时,`ng-options` 需改用 `(key, value)` 语法:`ng-options="x for (x, y) in sites"` 中 `x` 为键、`y` 为值,下拉列表向用户展示键名 `x`,而 `ng-model` 实际接收的是该键对应的值 `y`。本站离线实测选项标签为 `["site01", "site02", "site03"]`,选中 `site02` 后模型值落定为 `BlueSky`。

键值对的值 `y` 同样可以是嵌套对象(例如 `cars` 中 `car01`~`car03` 各自包含 `brand`、`model`、`color` 字段):使用 `x for (x, y) in cars` 时,菜单显示 `car01`/`car02`/`car03` 且选中结果为对应车辆对象(实测选中首项读取 `Ford|Mustang|red`);若不希望暴露内部键名,可直接以嵌套属性作展示文本——写成 `ng-options="y.brand for (x, y) in cars"`,本站实测菜单标签显示为 `["Ford", "Fiat", "Volvo"]`,选中 `Volvo` 后模型完整持有 `{brand: "Volvo", model: "XC90", color: "black"}`。

离线 Chromium 核验 ng-options 与 ng-repeat 对象绑定及键值对象数据源

含完整源码 · 249 行
展开查看收起
python
"""Offline Playwright Chromium lab for AngularJS Ch 11: select."""
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 Select Lab</title></head>
<body>
  <div id="case-basic">
    <select id="sel-names"></select>
    <span id="out-basic"></span>
  </div>

  <div id="case-repeat-vs-options">
    <select id="sel-repeat"></select>
    <h1 id="out-repeat"></h1>
    <select id="sel-options"></select>
    <h1 id="out-opt-site"></h1>
    <p id="out-opt-url"></p>
  </div>

  <div id="case-object-source">
    <select id="sel-obj-str"></select>
    <h1 id="out-obj-str"></h1>
  </div>

  <div id="case-object-nested">
    <select id="sel-car-key"></select>
    <div id="out-car-key"></div>
    <select id="sel-car-brand"></select>
    <div id="out-car-brand"></div>
  </div>

  <script>
  // Minimal offline AngularJS 1.x ng-options / ng-repeat equivalence harness
  (function () {
    const names = ["Google", "BlueSky", "Taobao"];
    const sitesArr = [
      { site: "Google", url: "https://www.google.com" },
      { site: "BlueSky", url: "https://example.org/bluesky" },
      { site: "Taobao", url: "https://www.taobao.com" }
    ];
    const sitesObj = { site01: "Google", site02: "BlueSky", site03: "Taobao" };
    const carsObj = {
      car01: { brand: "Ford", model: "Mustang", color: "red" },
      car02: { brand: "Fiat", model: "500", color: "white" },
      car03: { brand: "Volvo", model: "XC90", color: "black" }
    };

    const state = {
      selectedName: names[0], // ng-init="selectedName = names[0]"
      selectedRepeat: null,
      selectedSiteObj: null,
      selectedObjStr: null,
      selectedCarKey: null,
      selectedCarBrand: null
    };

    // 1. ng-options="x for x in names" with ng-init
    const selNames = document.getElementById("sel-names");
    names.forEach((n, idx) => {
      const opt = document.createElement("option");
      opt.value = "string:" + n;
      opt.textContent = n;
      if (n === state.selectedName) opt.selected = true;
      selNames.appendChild(opt);
    });
    const renderBasic = () => {
      document.getElementById("out-basic").textContent = state.selectedName;
    };
    selNames.addEventListener("change", () => {
      const idx = selNames.selectedIndex;
      state.selectedName = names[idx];
      renderBasic();
    });
    renderBasic();

    // 2a. ng-repeat="x in sites" value="{{x.url}}" (binds string only)
    const selRepeat = document.getElementById("sel-repeat");
    sitesArr.forEach((item) => {
      const opt = document.createElement("option");
      opt.value = item.url;
      opt.textContent = item.site;
      selRepeat.appendChild(opt);
    });
    selRepeat.addEventListener("change", () => {
      state.selectedRepeat = selRepeat.value;
      document.getElementById("out-repeat").textContent = "你选择的是: " + state.selectedRepeat;
    });

    // 2b. ng-options="x.site for x in sites" (binds full JS object)
    const selOptions = document.getElementById("sel-options");
    sitesArr.forEach((item, idx) => {
      const opt = document.createElement("option");
      opt.value = "object:" + idx;
      opt.textContent = item.site;
      selOptions.appendChild(opt);
    });
    selOptions.addEventListener("change", () => {
      state.selectedSiteObj = sitesArr[selOptions.selectedIndex];
      document.getElementById("out-opt-site").textContent = "你选择的是: " + state.selectedSiteObj.site;
      document.getElementById("out-opt-url").textContent = "网址为: " + state.selectedSiteObj.url;
    });

    // 3. ng-options="x for (x, y) in sitesObj" (label = key x, value = y)
    const selObjStr = document.getElementById("sel-obj-str");
    const siteEntries = Object.entries(sitesObj);
    siteEntries.forEach(([k, v]) => {
      const opt = document.createElement("option");
      opt.value = k;
      opt.textContent = k;
      selObjStr.appendChild(opt);
    });
    selObjStr.addEventListener("change", () => {
      const [, v] = siteEntries[selObjStr.selectedIndex];
      state.selectedObjStr = v;
      document.getElementById("out-obj-str").textContent = "你选择的值是: " + state.selectedObjStr;
    });

    // 4a. ng-options="x for (x, y) in carsObj" (label = key x, value = object y)
    const selCarKey = document.getElementById("sel-car-key");
    const carEntries = Object.entries(carsObj);
    carEntries.forEach(([k]) => {
      const opt = document.createElement("option");
      opt.value = k;
      opt.textContent = k;
      selCarKey.appendChild(opt);
    });
    selCarKey.addEventListener("change", () => {
      const [, y] = carEntries[selCarKey.selectedIndex];
      state.selectedCarKey = y;
      document.getElementById("out-car-key").textContent =
        y.brand + "|" + y.model + "|" + y.color;
    });

    // 4b. ng-options="y.brand for (x, y) in carsObj" (label = y.brand, value = object y)
    const selCarBrand = document.getElementById("sel-car-brand");
    carEntries.forEach(([k, y]) => {
      const opt = document.createElement("option");
      opt.value = k;
      opt.textContent = y.brand;
      selCarBrand.appendChild(opt);
    });
    selCarBrand.addEventListener("change", () => {
      const [, y] = carEntries[selCarBrand.selectedIndex];
      state.selectedCarBrand = y;
      document.getElementById("out-car-brand").textContent =
        y.brand + "|" + y.model + "|" + y.color;
    });

    window.__labState = state;
  })();
  </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: ng-options array + ng-init default selection + change
            init_val = page.text_content("#out-basic")
            init_opts = page.eval_on_selector_all("#sel-names option", "els => els.map(e => e.textContent)")
            page.select_option("#sel-names", index=2)
            after_val = page.text_content("#out-basic")
            actual1 = {"options": init_opts, "initial": init_val, "after_select_2": after_val}
            expected1 = {"options": ["Google", "BlueSky", "Taobao"], "initial": "Google", "after_select_2": "Taobao"}
            cases.append({"name": "ng_options_array_and_ng_init", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})

            # Case 2: ng-repeat binds string value vs ng-options binds object
            page.select_option("#sel-repeat", index=1)
            page.select_option("#sel-options", index=1)
            actual2 = page.evaluate("""() => ({
                repeatType: typeof window.__labState.selectedRepeat,
                repeatValue: window.__labState.selectedRepeat,
                repeatDom: document.getElementById("out-repeat").textContent,
                optionsType: typeof window.__labState.selectedSiteObj,
                optionsObj: window.__labState.selectedSiteObj,
                optionsSiteDom: document.getElementById("out-opt-site").textContent,
                optionsUrlDom: document.getElementById("out-opt-url").textContent
            })""")
            expected2 = {
                "repeatType": "string",
                "repeatValue": "https://example.org/bluesky",
                "repeatDom": "你选择的是: https://example.org/bluesky",
                "optionsType": "object",
                "optionsObj": {"site": "BlueSky", "url": "https://example.org/bluesky"},
                "optionsSiteDom": "你选择的是: BlueSky",
                "optionsUrlDom": "网址为: https://example.org/bluesky",
            }
            cases.append({"name": "ng_repeat_string_vs_ng_options_object", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})

            # Case 3: object data source (key as label, value as model)
            obj_labels = page.eval_on_selector_all("#sel-obj-str option", "els => els.map(e => e.textContent)")
            page.select_option("#sel-obj-str", index=1)
            actual3 = {
                "labels": obj_labels,
                "selected_value": page.evaluate("window.__labState.selectedObjStr"),
                "dom": page.text_content("#out-obj-str"),
            }
            expected3 = {
                "labels": ["site01", "site02", "site03"],
                "selected_value": "BlueSky",
                "dom": "你选择的值是: BlueSky",
            }
            cases.append({"name": "object_source_key_label_value_model", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})

            # Case 4: object-of-objects with key label vs nested property y.brand label
            key_labels = page.eval_on_selector_all("#sel-car-key option", "els => els.map(e => e.textContent)")
            brand_labels = page.eval_on_selector_all("#sel-car-brand option", "els => els.map(e => e.textContent)")
            page.select_option("#sel-car-key", index=0)
            page.select_option("#sel-car-brand", index=2)
            actual4 = {
                "key_labels": key_labels,
                "key_selected_dom": page.text_content("#out-car-key"),
                "brand_labels": brand_labels,
                "brand_selected_dom": page.text_content("#out-car-brand"),
                "brand_selected_obj": page.evaluate("window.__labState.selectedCarBrand"),
            }
            expected4 = {
                "key_labels": ["car01", "car02", "car03"],
                "key_selected_dom": "Ford|Mustang|red",
                "brand_labels": ["Ford", "Fiat", "Volvo"],
                "brand_selected_dom": "Volvo|XC90|black",
                "brand_selected_obj": {"brand": "Volvo", "model": "XC90", "color": "black"},
            }
            cases.append({"name": "object_nested_value_and_property_label", "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-init 默认首项 Google、ng-repeat 返回 string 与 ng-options 返回 object 的差异,以及 (x, y) 键显示与 y.brand 属性显示均绑定对应值对象。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

ng-repeat 生成的 HTML option 只能通过 value 属性提交字符串;ng-options 可直接把数组元素或键值对的 value 对象绑定到 ng-model,使视图与控制器能同时读取该对象的多个字段。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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