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

AngularJS 过滤器

系统梳理 AngularJS 管道过滤器语法、五大常用内置过滤器(currency、filter、lowercase、orderBy、uppercase)在表达式与 ng-repeat 中的链式组合,以及自定义 reverse 过滤器。

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

学完这一章,你能够

过滤器语法与五大常用内置过滤器

AngularJS 过滤器(Filter)用于在不修改原始模型的前提下转换展示数据,通过管道字符 `|` 串联到模板表达式或指令中。常用的五个内置过滤器分别负责货币格式化(`currency`)、数组子集筛选(`filter`)、字母转小写(`lowercase`)、数组排序(`orderBy`)以及字母转大写(`uppercase`),具体用途见下方对照表。

在表达式中使用大小写与货币过滤器

在双大括号表达式中直接写 `{{ 表达式 | 过滤器名 }}` 即可完成格式化。沿用人员控制器中的 `lastName = "Doe"`,`{{ lastName | uppercase }}` 将文本全部转为大写,`{{ lastName | lowercase }}` 则全部转为小写。本站离线 Chromium 实测分别输出 `"DOE"` 与 `"doe"`。

`currency` 过滤器将数值格式化为带千分位与两位小数的货币字符串,默认使用美元符号 `$`,也可通过冒号传参指定其他符号(如 `currency:'¥'`)。本站实测:当 `quantity = 2`、`price = 19.5` 时 `{{ (quantity * price) | currency }}` 输出 `"$39.00"`;将数量与单价改为 `1200` 与 `1.25` 后,默认格式更新为 `"$1,500.00"`,指定符号 `'¥'` 时输出 `"¥1,500.00"`。

在指令中排序筛选与注册自定义过滤器

过滤器同样可以直接挂在 `ng-repeat` 等指令的集合表达式后。使用 `ng-repeat="x in names | orderBy:'country'"` 会按每项对象的 `country` 字段升序排列数组。本站离线实测将 3 条记录按国家字母顺序排列为 `["Kai, Denmark", "Jani, Norway", "Hege, Sweden"]`。

若需要按用户输入实时过滤列表,可将输入框绑定到 `ng-model="test"`,并在 `ng-repeat` 中以冒号传入模型名,同时继续串联排序与项内大写过滤器:`ng-repeat="x in names | filter:test | orderBy:'country'"` 搭配 `{{ (x.name | uppercase) + ', ' + x.country }}`。本站实测:空查询输出全部 3 项 `["KAI, Denmark", "JANI, Norway", "HEGE, Sweden"]`;输入 `"sw"` 仅保留 `["HEGE, Sweden"]`;输入 `"ja"` 仅保留 `["JANI, Norway"]`。

当内置过滤器不足以满足业务格式化需求时,可调用 `app.filter('过滤器名', function() { return function(input) { ... }; })` 注册自定义过滤器(工厂函数同样支持依赖注入)。例如实现将字符串倒序输出的 `reverse` 过滤器:本站实测输入 `"BlueSky"` 输出 `"ykSeulB"`,改输入 `"Angular"` 后即时输出 `"ralugnA"`。

AngularJS 常用内置过滤器对照表

过滤器作用与转换规则
currency将数字格式化为货币文本(默认美元符号 $、千分位与两位小数,可传自定义符号)。
filter依据字符串、对象条件或断言函数从数组中筛选符合条件的子集。
lowercase将输入字符串中的所有英文字母转换为小写。
orderBy依据指定属性名、表达式或比较器对数组项排序。
uppercase将输入字符串中的所有英文字母转换为大写。

验证 uppercase/lowercase/currency/orderBy/filter 链式组合与自定义 reverse 过滤器

python · 阅读源码
"""Offline Playwright Chromium lab for AngularJS Ch 08 (filters)."""
import json
from playwright.sync_api import sync_playwright

HTML_PAGE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS Filters Offline Lab</title></head>
<body>
  <div id="sec-case" ng-app="appCase" ng-controller="personCtrl">
    <p id="out-upper">{{ lastName | uppercase }}</p>
    <p id="out-lower">{{ lastName | lowercase }}</p>
  </div>

  <div id="sec-currency" ng-app="appCurrency" ng-controller="costCtrl">
    <input id="cur-qty" type="number" ng-model="quantity">
    <input id="cur-price" type="number" ng-model="price">
    <p id="out-usd">{{ (quantity * price) | currency }}</p>
    <p id="out-cny">{{ (quantity * price) | currency:'¥' }}</p>
  </div>

  <div id="sec-orderby" ng-app="appOrder" ng-controller="namesCtrl">
    <ul id="ul-order"></ul>
  </div>

  <div id="sec-filter" ng-app="appFilter" ng-controller="namesCtrl">
    <input id="flt-input" type="text" ng-model="test">
    <ul id="ul-filter"></ul>
  </div>

  <div id="sec-custom" ng-app="appCustom" ng-controller="revCtrl">
    <input id="rev-input" type="text" ng-model="msg">
    <p id="out-rev">{{ msg | reverse }}</p>
  </div>

  <script>
    (function () {
      const builtinFilters = {
        uppercase(val) {
          return String(val ?? "").toUpperCase();
        },
        lowercase(val) {
          return String(val ?? "").toLowerCase();
        },
        currency(val, symbol = "$") {
          const num = Number(val);
          if (Number.isNaN(num)) return "";
          const abs = Math.abs(num).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
          return (num < 0 ? "-" : "") + symbol + abs;
        },
        orderBy(arr, key) {
          return [...arr].sort((a, b) => String(a[key]).localeCompare(String(b[key])));
        },
        filter(arr, query) {
          if (!query) return [...arr];
          const q = String(query).toLowerCase();
          return arr.filter((item) =>
            Object.values(item).some((v) => String(v).toLowerCase().includes(q))
          );
        }
      };

      const customFilters = {};
      function registerFilter(name, factory) {
        customFilters[name] = factory();
      }
      registerFilter("reverse", function () {
        return function (text) {
          return String(text ?? "").split("").reverse().join("");
        };
      });

      function applyFilterChain(expr, scope) {
        const segments = expr.split("|").map((s) => s.trim());
        let val = new Function("scope", "with(scope){ return (" + segments[0] + "); }")(scope);
        for (let i = 1; i < segments.length; i++) {
          const colonIdx = segments[i].indexOf(":");
          const fname = colonIdx === -1 ? segments[i] : segments[i].slice(0, colonIdx).trim();
          const argExpr = colonIdx === -1 ? null : segments[i].slice(colonIdx + 1).trim();
          const fn = customFilters[fname] || builtinFilters[fname];
          const arg = argExpr !== null
            ? new Function("scope", "with(scope){ return (" + argExpr + "); }")(scope)
            : undefined;
          val = argExpr !== null ? fn(val, arg) : fn(val);
        }
        return val === undefined || val === null ? "" : String(val);
      }

      function bindSimple(root, scope) {
        const textBindings = [];
        const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
        let n;
        while ((n = walker.nextNode())) {
          if (n.nodeValue && n.nodeValue.includes("{{")) {
            textBindings.push({ node: n, tpl: n.nodeValue });
          }
        }
        function render() {
          for (const b of textBindings) {
            b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => applyFilterChain(ex.trim(), scope));
          }
        }
        root.querySelectorAll("[ng-model]").forEach((el) => {
          const prop = el.getAttribute("ng-model");
          if (scope[prop] !== undefined) el.value = String(scope[prop]);
          el.addEventListener("input", () => {
            scope[prop] = el.type === "number" ? Number(el.value) : el.value;
            render();
          });
        });
        render();
      }

      // 1. uppercase / lowercase
      bindSimple(document.getElementById("sec-case"), { lastName: "Doe" });

      // 2. currency
      bindSimple(document.getElementById("sec-currency"), { quantity: 2, price: 19.5 });

      // 3. orderBy:'country'
      const namesData = [
        { name: "Jani", country: "Norway" },
        { name: "Hege", country: "Sweden" },
        { name: "Kai", country: "Denmark" }
      ];
      const ulOrder = document.getElementById("ul-order");
      for (const x of builtinFilters.orderBy(namesData, "country")) {
        const li = document.createElement("li");
        li.textContent = x.name + ", " + x.country;
        ulOrder.appendChild(li);
      }

      // 4. filter:test | orderBy:'country' + uppercase
      const fltInput = document.getElementById("flt-input");
      const ulFilter = document.getElementById("ul-filter");
      function renderFiltered() {
        ulFilter.innerHTML = "";
        const filtered = builtinFilters.orderBy(
          builtinFilters.filter(namesData, fltInput.value),
          "country"
        );
        for (const x of filtered) {
          const li = document.createElement("li");
          li.textContent = builtinFilters.uppercase(x.name) + ", " + x.country;
          ulFilter.appendChild(li);
        }
      }
      fltInput.addEventListener("input", renderFiltered);
      renderFiltered();

      // 5. custom reverse filter
      bindSimple(document.getElementById("sec-custom"), { msg: "BlueSky" });
    })();
  </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)
        page = browser.new_page()
        page.set_content(HTML_PAGE)

        # Case 1: uppercase & lowercase
        actual_1 = {
            "uppercase": page.locator("#out-upper").text_content(),
            "lowercase": page.locator("#out-lower").text_content(),
        }
        expected_1 = {"uppercase": "DOE", "lowercase": "doe"}
        cases.append({
            "name": "expression_uppercase_and_lowercase",
            "expected": expected_1,
            "actual": actual_1,
            "passed": actual_1 == expected_1,
        })

        # Case 2: currency formatting default USD and custom CNY symbol
        init_usd = page.locator("#out-usd").text_content()
        page.fill("#cur-qty", "1200")
        page.fill("#cur-price", "1.25")
        upd_usd = page.locator("#out-usd").text_content()
        upd_cny = page.locator("#out-cny").text_content()
        actual_2 = {"init_usd": init_usd, "updated_usd": upd_usd, "updated_cny": upd_cny}
        expected_2 = {"init_usd": "$39.00", "updated_usd": "$1,500.00", "updated_cny": "¥1,500.00"}
        cases.append({
            "name": "expression_currency_filter",
            "expected": expected_2,
            "actual": actual_2,
            "passed": actual_2 == expected_2,
        })

        # Case 3: orderBy:'country'
        actual_3 = {"ordered": page.locator("#ul-order li").all_text_contents()}
        expected_3 = {"ordered": ["Kai, Denmark", "Jani, Norway", "Hege, Sweden"]}
        cases.append({
            "name": "directive_orderby_filter",
            "expected": expected_3,
            "actual": actual_3,
            "passed": actual_3 == expected_3,
        })

        # Case 4: filter:test | orderBy:'country' + uppercase
        all_items = page.locator("#ul-filter li").all_text_contents()
        page.fill("#flt-input", "sw")
        sw_items = page.locator("#ul-filter li").all_text_contents()
        page.fill("#flt-input", "ja")
        ja_items = page.locator("#ul-filter li").all_text_contents()
        actual_4 = {"empty_query": all_items, "query_sw": sw_items, "query_ja": ja_items}
        expected_4 = {
            "empty_query": ["KAI, Denmark", "JANI, Norway", "HEGE, Sweden"],
            "query_sw": ["HEGE, Sweden"],
            "query_ja": ["JANI, Norway"],
        }
        cases.append({
            "name": "directive_input_filter_and_chaining",
            "expected": expected_4,
            "actual": actual_4,
            "passed": actual_4 == expected_4,
        })

        # Case 5: custom reverse filter
        init_rev = page.locator("#out-rev").text_content()
        page.fill("#rev-input", "Angular")
        upd_rev = page.locator("#out-rev").text_content()
        actual_5 = {"initial": init_rev, "updated": upd_rev}
        expected_5 = {"initial": "ykSeulB", "updated": "ralugnA"}
        cases.append({
            "name": "custom_reverse_filter",
            "expected": expected_5,
            "actual": actual_5,
            "passed": actual_5 == expected_5,
        })

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 'Doe' 转为 'DOE'/'doe';货币格式 '$39.00'、'$1,500.00' 与 '¥1,500.00';orderBy 按国名排序;filter 联查 'sw' 与 'ja' 命中单条;reverse 反转 'BlueSky' 与 'Angular'。
验证 uppercase/lowercase/currency/orderBy/filter 链式组合与自定义 reverse 过滤器

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

当前源码 SHA256:7d81a19468ebe511fb32bbdb48ce0b0feb3a30293165374543e2b3ab727d62d9

下载本站示例源码

本地运行

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

下载AngularJS 过滤器实验

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

ZIP SHA256:be669eb7c8249cae860855c33416444286d6d27d34f9da91e3023079a6f6ad82

常见错误与边界

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

练习与解答

在 ng-repeat 中连续书写 filter:test | orderBy:'country' 时执行顺序是怎样的?如果把 orderBy 放在 filter 前面有什么性能差异?

展开参考解答

管道过滤器严格按从左到右顺序执行:先执行 filter:test 缩小数组规模,再对筛选后的子集按 country 排序;若反过来先排序再过滤,会在每次脏检查时对全量数组排序,数据量大时开销更高。

规范与官方依据