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

AngularJS 指令

系统讲解 AngularJS 内置核心指令(ng-app、ng-init、ng-model、ng-repeat)的职责与数据绑定机制,以及自定义指令的驼峰-短横线命名和 E/A/C/M 四类调用限制。

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

学完这一章,你能够

内置核心指令与双向数据绑定

AngularJS 将带有 `ng-` 前缀的扩展 HTML 属性称为指令(Directive),既内置了一批覆盖引导、绑定、循环与验证的常用指令,也允许按业务需求注册自定义指令。其中 `ng-app` 将所在元素标记为应用程序根所有者,`ng-init` 为作用域提供初始值,`ng-model` 将表单控件值与作用域模型建立关联;完整内置指令清单可在官方 API 参考手册中检索。

数据绑定机制负责把模板表达式(如 `{{ firstName }}`)与作用域模型实时同步。将 `ng-model="firstName"` 挂到输入框后,用户输入立即回写模型并刷新插值;同理在价格计算器中同时绑定 `quantity` 与 `price` 两个数字输入框,修改任意一侧即可实时更新总价 `{{ quantity * price }}`。本站离线 Chromium 实测:姓名从初始 `"John"` 改输入 `"Grace"` 后视图同步变为 `"Grace"`,价格计算器从 `1 × 5 = 5` 修改为 `3 × 12` 后即时更新为 `"36"`。

`ng-repeat` 指令会针对集合中的每一项克隆一次宿主 HTML 元素。无论是字符串数组 `['Jani','Hege','Kai']` 还是包含 `{name, country}` 属性的对象数组,都可以用 `ng-repeat="x in names"` 逐项展开为 `<li>` 列表。本站实测分别准确克隆出 3 条字符串项 `["Jani", "Hege", "Kai"]` 与 3 条对象组合项 `["Jani, Norway", "Hege, Sweden", "Kai, Denmark"]`;这种对象数组结构可直接映射后端数据库的增删改查(CRUD)记录集。

四项基础内置指令职责细化

`ng-app` 定义 AngularJS 应用的根元素,页面加载完毕后会自动引导初始化;当传入模块名(如 `ng-app="myModule"`)时,根元素会连接到对应的代码模块。

`ng-init` 为应用作用域定义初始值,但实际开发通常不在 HTML 中硬编码初始状态,而是交由控制器或模块统一管理。

`ng-model` 除绑定控件与数据外,还提供四项表单支撑能力:一是按 `number`、`email`、`required` 等规则执行类型验证;二是维护 `invalid`、`dirty`、`touched`、`error` 等状态标志;三是根据状态自动增删 HTML 元素的 CSS 类;四是将控件状态接入 HTML 表单控制器。`ng-repeat` 则对数组或对象集合的每个条目执行一次 DOM 克隆与独立子作用域绑定。

自定义指令命名与 restrict 调用限制

调用模块的 `.directive(name, factory)` 方法即可注册自定义指令。命名遵循严格的驼峰转短横线规则:JavaScript 中使用驼峰式注册(如 `skyBanner`),在 HTML 模板中调用时则改写为连字符分隔的 `sky-banner`。AngularJS 支持四种调用形式:元素名(`<sky-notice></sky-notice>`)、属性(`<div sky-notice></div>`)、CSS 类名(`<div class="sky-notice"></div>`)以及注释(`<!-- directive: sky-notice -->`,需配合 `replace: true` 才会替换出可见节点)。

在指令定义对象中设置 `restrict` 属性可限定合法的调用方式:`E` 表示元素名、`A` 表示属性、`C` 表示类名、`M` 表示注释,且支持自由组合;未显式指定时默认值为 `"EA"`(允许元素名和属性,忽略类名与注释)。本站离线 Chromium 实测完整验证三组配置:默认 `EA` 的 `skyBanner` 仅展开元素与属性两处(`h1_count = 2`),类名与注释不触发;配置 `restrict: "EACM"` 与 `replace: true` 的 `skyNotice` 四种写法均输出 `"四模式指令!"`;配置 `restrict: "A"` 的 `skyOnlyAttr` 仅在属性调用处生效,元素标签写法保持为空。

ng-init 与控制器初始化对比提示

提示主题实践说明
优先用控制器初始化数据直接在标签上写 ng-init 难以复用与维护,正式业务中应通过控制器向 $scope 注入初始数据。

对象数组与数据库 CRUD 映射提示

提示主题实践说明
对象数组对应 CRUD 数据记录ng-repeat 渲染的对象数组天然对应数据库的增(Create)、读(Read)、改(Update)、删(Delete)记录集合,可直接衔接接口数据。

验证 ng-model 计算器、ng-repeat 对象数组及自定义指令 EA/EACM/A 限制

python · 阅读源码
"""Offline Playwright Chromium lab for AngularJS Ch 04 (directives)."""
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 Directives Offline Lab</title></head>
<body>
  <div id="sec-bind" ng-app="" ng-init="firstName='John'">
    <input id="fn-inp" type="text" ng-model="firstName">
    <p id="fn-out">{{ firstName }}</p>
  </div>

  <div id="sec-calc" ng-app="" ng-init="quantity=1;price=5">
    <input id="qty-inp" type="number" ng-model="quantity">
    <input id="price-inp" type="number" ng-model="price">
    <p id="total-out">{{ quantity * price }}</p>
  </div>

  <div id="sec-rep-arr" ng-app="" ng-init="names=['Jani','Hege','Kai']">
    <ul id="ul-arr">
      <li ng-repeat="x in names">{{ x }}</li>
    </ul>
  </div>

  <div id="sec-rep-obj" ng-app="" ng-init="names=[{name:'Jani',country:'Norway'},{name:'Hege',country:'Sweden'},{name:'Kai',country:'Denmark'}]">
    <ul id="ul-obj">
      <li ng-repeat="x in names">{{ x.name + ', ' + x.country }}</li>
    </ul>
  </div>

  <div id="sec-dir-ea" ng-app="eaApp">
    <sky-banner id="ea-elem"></sky-banner>
    <div id="ea-attr" sky-banner></div>
    <div id="ea-cls" class="sky-banner"></div>
    <!-- directive: sky-banner -->
  </div>

  <div id="sec-dir-eacm" ng-app="eacmApp">
    <sky-notice id="eacm-elem"></sky-notice>
    <div id="eacm-attr" sky-notice></div>
    <div id="eacm-cls" class="sky-notice"></div>
    <div id="eacm-comment-wrap"><!-- directive: sky-notice --></div>
  </div>

  <div id="sec-dir-a" ng-app="aOnlyApp">
    <sky-only-attr id="aonly-elem"></sky-only-attr>
    <div id="aonly-attr" sky-only-attr></div>
  </div>

  <script>
    (function () {
      const modules = {};
      window.angular = {
        module(name, deps) {
          if (deps) {
            const mod = { _directives: {} };
            mod.directive = function (camelName, factory) {
              mod._directives[camelName] = factory();
              return mod;
            };
            modules[name] = mod;
            return mod;
          }
          return modules[name];
        }
      };

      angular.module("eaApp", []).directive("skyBanner", function () {
        return { template: "<h1>自定义指令!</h1>" };
      });
      angular.module("eacmApp", []).directive("skyNotice", function () {
        return { restrict: "EACM", replace: true, template: "<h1>四模式指令!</h1>" };
      });
      angular.module("aOnlyApp", []).directive("skyOnlyAttr", function () {
        return { restrict: "A", template: "<h1>仅属性指令!</h1>" };
      });

      function camelToKebab(str) {
        return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
      }

      function evalExpr(expr, scope) {
        const v = new Function("scope", "with(scope){ return (" + expr + "); }")(scope);
        return v === undefined || v === null ? "" : String(v);
      }

      function compileInterpolations(el, scope) {
        const textBindings = [];
        const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
        let n;
        while ((n = walker.nextNode())) {
          if (n.nodeValue && n.nodeValue.includes("{{")) {
            textBindings.push({ node: n, tpl: n.nodeValue });
          }
        }
        return function render() {
          for (const b of textBindings) {
            b.node.nodeValue = b.tpl.replace(/\{\{([^}]+)\}\}/g, (_, ex) => evalExpr(ex.trim(), scope));
          }
        };
      }

      function applyDirectives(root, mod) {
        for (const [camelName, ddo] of Object.entries(mod._directives)) {
          const kebab = camelToKebab(camelName);
          const restrict = ddo.restrict || "EA";
          if (restrict.includes("E")) {
            root.querySelectorAll(kebab).forEach((el) => {
              el.innerHTML = ddo.template;
            });
          }
          if (restrict.includes("A")) {
            root.querySelectorAll("[" + kebab + "]").forEach((el) => {
              el.innerHTML = ddo.template;
            });
          }
          if (restrict.includes("C")) {
            root.querySelectorAll("." + kebab).forEach((el) => {
              el.innerHTML = ddo.template;
            });
          }
          if (restrict.includes("M")) {
            const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
            const comments = [];
            let c;
            while ((c = walker.nextNode())) comments.push(c);
            for (const cm of comments) {
              const m = cm.nodeValue.trim().match(/^directive:\s*([a-z0-9-]+)$/);
              if (m && m[1] === kebab) {
                const holder = document.createElement("div");
                holder.innerHTML = ddo.template;
                if (ddo.replace && holder.firstElementChild) {
                  cm.parentNode.replaceChild(holder.firstElementChild, cm);
                }
              }
            }
          }
        }
      }

      document.querySelectorAll("[ng-app]").forEach((root) => {
        const appName = root.getAttribute("ng-app");
        if (appName && modules[appName]) {
          applyDirectives(root, modules[appName]);
        }
        const scope = {};
        const initCode = root.getAttribute("ng-init");
        if (initCode) {
          const initProxy = new Proxy(scope, { has: () => true });
          new Function("scope", "with(scope){ " + initCode + "; }")(initProxy);
        }

        const repeatEls = Array.from(root.querySelectorAll("[ng-repeat]"));
        for (const tplEl of repeatEls) {
          const expr = tplEl.getAttribute("ng-repeat").trim();
          const m = expr.match(/^(\w+)\s+in\s+(\w+)$/);
          if (!m) continue;
          const [, itemVar, listVar] = m;
          const parent = tplEl.parentNode;
          const items = scope[listVar] || [];
          tplEl.removeAttribute("ng-repeat");
          const cloneBase = tplEl.cloneNode(true);
          parent.removeChild(tplEl);
          for (const item of items) {
            const childScope = Object.create(scope);
            childScope[itemVar] = item;
            const clone = cloneBase.cloneNode(true);
            compileInterpolations(clone, childScope)();
            parent.appendChild(clone);
          }
        }

        const render = compileInterpolations(root, 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();
      });
    })();
  </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: ng-model two-way binding + price calculator
        init_fn = page.locator("#fn-out").text_content()
        page.fill("#fn-inp", "Grace")
        upd_fn = page.locator("#fn-out").text_content()
        init_total = page.locator("#total-out").text_content()
        page.fill("#qty-inp", "3")
        page.fill("#price-inp", "12")
        upd_total = page.locator("#total-out").text_content()
        actual_1 = {
            "init_first_name": init_fn,
            "updated_first_name": upd_fn,
            "init_total": init_total,
            "updated_total": upd_total,
        }
        expected_1 = {
            "init_first_name": "John",
            "updated_first_name": "Grace",
            "init_total": "5",
            "updated_total": "36",
        }
        cases.append({
            "name": "ng_model_first_name_and_price_calc",
            "expected": expected_1,
            "actual": actual_1,
            "passed": actual_1 == expected_1,
        })

        # Case 2: ng-repeat on string array & object array
        actual_2 = {
            "string_items": page.locator("#ul-arr li").all_text_contents(),
            "object_items": page.locator("#ul-obj li").all_text_contents(),
        }
        expected_2 = {
            "string_items": ["Jani", "Hege", "Kai"],
            "object_items": ["Jani, Norway", "Hege, Sweden", "Kai, Denmark"],
        }
        cases.append({
            "name": "ng_repeat_primitive_and_object_arrays",
            "expected": expected_2,
            "actual": actual_2,
            "passed": actual_2 == expected_2,
        })

        # Case 3: default restrict="EA" matches element & attribute, ignores class & comment
        actual_3 = {
            "element": page.locator("#ea-elem").text_content().strip(),
            "attribute": page.locator("#ea-attr").text_content().strip(),
            "class_ignored": page.locator("#ea-cls").text_content().strip(),
            "h1_count": page.locator("#sec-dir-ea h1").count(),
        }
        expected_3 = {
            "element": "自定义指令!",
            "attribute": "自定义指令!",
            "class_ignored": "",
            "h1_count": 2,
        }
        cases.append({
            "name": "custom_directive_camel_to_kebab_ea",
            "expected": expected_3,
            "actual": actual_3,
            "passed": actual_3 == expected_3,
        })

        # Case 4: restrict="EACM" supports element, attribute, class, comment
        actual_4 = {
            "element": page.locator("#eacm-elem").text_content().strip(),
            "attribute": page.locator("#eacm-attr").text_content().strip(),
            "class": page.locator("#eacm-cls").text_content().strip(),
            "comment": page.locator("#eacm-comment-wrap").text_content().strip(),
        }
        expected_4 = {
            "element": "四模式指令!",
            "attribute": "四模式指令!",
            "class": "四模式指令!",
            "comment": "四模式指令!",
        }
        cases.append({
            "name": "custom_directive_four_modes_eacm",
            "expected": expected_4,
            "actual": actual_4,
            "passed": actual_4 == expected_4,
        })

        # Case 5: restrict="A" restricts to attribute only
        actual_5 = {
            "element_ignored": page.locator("#aonly-elem").text_content().strip(),
            "attribute_matched": page.locator("#aonly-attr").text_content().strip(),
        }
        expected_5 = {
            "element_ignored": "",
            "attribute_matched": "仅属性指令!",
        }
        cases.append({
            "name": "custom_directive_restrict_a_only",
            "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()
预期结果 · 待实际运行核验
  • 核对计算器 3×12=36、ng-repeat 克隆 3 个字符串与 3 个对象项;默认 EA 仅匹配元素和属性(2 处);EACM 四种调用均生效;restrict:'A' 仅匹配属性。
验证 ng-model 计算器、ng-repeat 对象数组及自定义指令 EA/EACM/A 限制

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

当前源码 SHA256:ba4ee150e7312ac7c888c41c3938c904baa811cf8ebc9b119d3a9e57bc83563e

下载本站示例源码

本地运行

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

下载AngularJS 指令实验

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

ZIP SHA256:e7f63eb907e3ae5f65dad459b57116521bc3d57fc4d495218fb3aec774e9ea92

常见错误与边界

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

练习与解答

在 AngularJS 中用 .directive('userCard', ...) 注册指令后,HTML 模板应写成什么名称?为什么仅用默认配置写 <div class='user-card'> 不会生效?

展开参考解答

驼峰名 userCard 在 HTML 中需写成短横线形式 user-card;因为 restrict 默认值为 'EA'(仅允许元素名和属性),必须显式包含 'C'(如 restrict: 'EAC')才会匹配 CSS 类名。

规范与官方依据