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

AngularJS 表达式

系统梳理 AngularJS 双大括号表达式与 ng-bind 在数字、字符串、对象和数组上的求值规则,并对比 AngularJS 表达式与原生 JavaScript 表达式的语义边界。

学完这一章,你能够

  • 系统梳理 AngularJS 双大括号表达式与 ng-bind 在数字、字符串、对象和数组上的求值规则,并对比 AngularJS 表达式与原生 JavaScript 表达式的语义边界。

双大括号表达式与 ng-bind 的关系

AngularJS 使用写在双大括号 `{{ expression }}` 中的表达式将数据绑定并输出到 HTML 模板指定位置,其求值输出效果与 `ng-bind` 指令等价(差别在于页面加载未编译前,`ng-bind` 不会短暂暴露 `{{...}}` 占位符)。表达式可包含字面量、算术或字符串运算符以及作用域变量,如 `{{ 5 + 5 }}` 或 `{{ firstName + " " + lastName }}`。

数字、字符串、对象与数组求值对照

AngularJS 表达式中的数字与算术运算行为与 JavaScript 一致:给定 `quantity=1; cost=5`,`{{ quantity * cost }}` 与 `<span ng-bind="quantity * cost"></span>` 均计算得到 `5`。本站离线实测同时验证动态重算:当作用域 `quantity` 改为 `4` 后,插值与 `ng-bind` 同步刷新为 `20`。需注意真实工程中极少用 `ng-init` 初始化业务数据,通常应放在控制器中维护。

字符串拼接同样遵循 JavaScript 习惯:初始化 `firstName='John'; lastName='Doe'` 后,`{{ firstName + " " + lastName }}` 与 `ng-bind="firstName + ' ' + lastName"` 在本站实测中均准确输出 `"John Doe"`(注意在 HTML 双引号属性内部嵌套字符串字面量时应使用单引号避免冲突)。

对于对象字面量(如 `person={firstName:'John', lastName:'Doe'}`),可通过点号属性访问 `person.lastName`;本站离线实测 `{{ person.lastName }}` 与 `ng-bind="person.lastName"` 均输出 `"Doe"`。

对于数组字面量(如 `points=[1, 15, 19, 2, 40]`),索引从 `0` 开始,因此第 3 个元素为 `points[2]`;本站实测 `{{ points[2] }}` 与 `ng-bind="points[2]"` 均准确返回 `"19"`。

AngularJS 表达式与 JavaScript 表达式的差异

虽然两者都支持字面量、操作符与变量,但 AngularJS 表达式具有四项明确边界:第一,它可以直接书写在 HTML 模板内并在当前 `$scope` 上下文而非全局 `window` 上求值;第二,对未定义或空值链访问采取宽容策略(如 `missingObj.deepProp` 返回空字符串而非抛出 `TypeError`);第三,不支持控制流语句(`if` 条件分支、`for`/`while` 循环以及 `throw` 异常语句);第四,支持使用管道符 `|` 调用过滤器格式化输出。本站离线实测全部核验:`'angular' | uppercase` 输出 `"ANGULAR"`,`missingObj.deepProp` 输出 `""`,而含 `if`/`for`/`throw` 的语句被解析器统一拦截。

ng-init 使用注意事项

提示主题工程建议
避免在生产模板中滥用 ng-initng-init 仅适合快速演示或配合 ng-repeat 局部别名,实际项目应在控制器中集中初始化模型数据以保证职责分离。

对照 {{}} 与 ng-bind 的数字/字符串/对象/数组求值及表达式语法限制

含完整源码 · 215 行
展开查看收起
python
"""Offline Playwright Chromium lab for AngularJS Ch 03 (expressions)."""
import json
from playwright.sync_api import sync_playwright

HTML_PAGE = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS Expressions Offline Lab</title></head>
<body>
  <div id="sec-num" ng-app="" ng-init="quantity=1;cost=5">
    <p id="num-interp">总价:{{ quantity * cost }}</p>
    <p id="num-bind">总价:<span id="num-bind-val" ng-bind="quantity * cost"></span></p>
  </div>

  <div id="sec-str" ng-app="" ng-init="firstName='John';lastName='Doe'">
    <p id="str-interp">{{ firstName + " " + lastName }}</p>
    <span id="str-bind" ng-bind="firstName + ' ' + lastName"></span>
  </div>

  <div id="sec-obj" ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
    <p id="obj-interp">{{ person.lastName }}</p>
    <span id="obj-bind" ng-bind="person.lastName"></span>
  </div>

  <div id="sec-arr" ng-app="" ng-init="points=[1,15,19,2,40]">
    <p id="arr-interp">{{ points[2] }}</p>
    <span id="arr-bind" ng-bind="points[2]"></span>
  </div>

  <div id="sec-diff" ng-app="" ng-init="label='angular'">
    <p id="diff-filter">{{ label | uppercase }}</p>
    <p id="diff-missing">{{ missingObj.deepProp }}</p>
  </div>

  <script>
    (function () {
      const filters = {
        uppercase: (v) => String(v).toUpperCase(),
        lowercase: (v) => String(v).toLowerCase(),
      };
      const FORBIDDEN_RE = /\b(if|else|for|while|do|switch|try|catch|throw|function)\b/;

      function safeEvalNgExpr(rawExpr, scope) {
        if (FORBIDDEN_RE.test(rawExpr)) {
          throw new Error("Disallowed JS statement in AngularJS expression");
        }
        const parts = rawExpr.split("|").map((s) => s.trim());
        let val;
        try {
          const fn = new Function("scope", "with(scope){ return (" + parts[0] + "); }");
          val = fn(scope);
        } catch (_) {
          val = undefined;
        }
        for (let i = 1; i < parts.length; i++) {
          const f = filters[parts[i]];
          if (f) val = f(val);
        }
        return val === undefined || val === null ? "" : String(val);
      }

      window.__testNgExpr = safeEvalNgExpr;

      document.querySelectorAll("[ng-app]").forEach((root) => {
        const scope = {};
        const initCode = root.getAttribute("ng-init");
        if (initCode) {
          const initProxy = new Proxy(scope, { has: () => true });
          new Function("scope", "with(scope){ " + initCode + "; }")(initProxy);
        }
        root.__scope = 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 });
          }
        }
        const bindEls = Array.from(root.querySelectorAll("[ng-bind]"));
        root.__render = function () {
          for (const b of textBindings) {
            b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => safeEvalNgExpr(ex.trim(), scope));
          }
          for (const el of bindEls) {
            el.textContent = safeEvalNgExpr(el.getAttribute("ng-bind"), scope);
          }
        };
        root.__render();
      });
    })();
  </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: Numbers interpolation vs ng-bind + dynamic update
        init_interp = page.locator("#num-interp").text_content()
        init_bind = page.locator("#num-bind-val").text_content()
        page.evaluate("""() => {
            const r = document.getElementById('sec-num');
            r.__scope.quantity = 4;
            r.__render();
        }""")
        updated_interp = page.locator("#num-interp").text_content()
        updated_bind = page.locator("#num-bind-val").text_content()
        actual_1 = {
            "init_interp": init_interp,
            "init_bind": init_bind,
            "updated_interp": updated_interp,
            "updated_bind": updated_bind,
        }
        expected_1 = {
            "init_interp": "总价:5",
            "init_bind": "5",
            "updated_interp": "总价:20",
            "updated_bind": "20",
        }
        cases.append({
            "name": "expression_numbers_interp_vs_ng_bind",
            "expected": expected_1,
            "actual": actual_1,
            "passed": actual_1 == expected_1,
        })

        # Case 2: Strings concatenation
        actual_2 = {
            "interp": page.locator("#str-interp").text_content(),
            "ng_bind": page.locator("#str-bind").text_content(),
        }
        expected_2 = {"interp": "John Doe", "ng_bind": "John Doe"}
        cases.append({
            "name": "expression_strings_concat",
            "expected": expected_2,
            "actual": actual_2,
            "passed": actual_2 == expected_2,
        })

        # Case 3: Objects property lookup
        actual_3 = {
            "interp": page.locator("#obj-interp").text_content(),
            "ng_bind": page.locator("#obj-bind").text_content(),
        }
        expected_3 = {"interp": "Doe", "ng_bind": "Doe"}
        cases.append({
            "name": "expression_objects_property",
            "expected": expected_3,
            "actual": actual_3,
            "passed": actual_3 == expected_3,
        })

        # Case 4: Arrays element indexing
        actual_4 = {
            "interp": page.locator("#arr-interp").text_content(),
            "ng_bind": page.locator("#arr-bind").text_content(),
        }
        expected_4 = {"interp": "19", "ng_bind": "19"}
        cases.append({
            "name": "expression_arrays_index",
            "expected": expected_4,
            "actual": actual_4,
            "passed": actual_4 == expected_4,
        })

        # Case 5: AngularJS vs JS expression differences
        rejected = page.evaluate("""() => {
            const results = {};
            for (const expr of ['if (true) { 1 }', 'for (var i=0;i<2;i++) {}', 'throw new Error("x")']) {
                try {
                    window.__testNgExpr(expr, {});
                    results[expr] = false;
                } catch (e) {
                    results[expr] = true;
                }
            }
            return results;
        }""")
        actual_5 = {
            "filter_uppercase": page.locator("#diff-filter").text_content(),
            "forgiving_undefined": page.locator("#diff-missing").text_content(),
            "disallows_if_for_throw": all(rejected.values()),
        }
        expected_5 = {
            "filter_uppercase": "ANGULAR",
            "forgiving_undefined": "",
            "disallows_if_for_throw": True,
        }
        cases.append({
            "name": "expression_limits_and_filter_diff",
            "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()
核对 quantity*cost 从 5 重算为 20、字符串拼接 'John Doe'、对象属性 'Doe'、数组 points[2]='19',以及过滤器 'ANGULAR'、空属性宽容返回 '' 与禁止 if/for/throw。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

第一,AngularJS 表达式在当前 $scope 而非 window 上求值且对 undefined 属性宽容;第二,禁止 if/for/throw 等控制流与异常语句;第三,原生支持管道过滤器 |。使用 ng-bind 在脚本加载完成前不会在页面上闪现原始双大括号标记。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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