AngularJS 模块
核对 AngularJS 模块定义与依赖数组语法、控制器与自定义指令注册、外部 JS 拆文件组织、避免全局命名空间污染及库脚本载入时机。
学完这一章,你能够
- 核对 AngularJS 模块定义与依赖数组语法、控制器与自定义指令注册、外部 JS 拆文件组织、避免全局命名空间污染及库脚本载入时机。
模块概念、创建方式与添加控制器
在 AngularJS 中,模块(Module)用于定义一个完整的应用程序,是控制器、指令、过滤器、服务等各组成部件的统一容器,绝大多数控制器都应归属于某个具体模块。调用 `angular.module("myApp", [])` 即可创建名为 `myApp` 的模块,该名称与 HTML 中 `ng-app="myApp"` 所声明的应用根节点一一对应;随后便可向模块挂载控制器、指令与过滤器。
在模块上调用 `app.controller("myCtrl", function($scope) { ... })` 并在视图元素添加 `ng-controller="myCtrl"`,即可把模型数据(如 `firstName = "John"`、`lastName = "Doe"`)注入视图模板(更多控制器细节可参阅 AngularJS 控制器章节)。本站离线 Chromium 实测验证了 `myApp` / `myCtrl` 挂载并准确渲染 `John Doe`。
向模块注册自定义指令
除了丰富的内置指令(完整清单见 AngularJS 官方指令参考手册),开发者还可通过 `app.directive(name, factory)` 为模块扩展自定义指令(进阶用法见 AngularJS 指令章节)。需要注意命名规范化规则:JavaScript 中使用驼峰式名称注册(如 `demoDirective`),在 HTML 模板属性中则须写作连字符短横线形式(`demo-directive`),工厂函数返回包含 `template` 的配置对象即可将模板内容注入宿主元素。本站离线 Chromium 实测将 `demoDirective` 规范化映射至 `demo-directive` 属性,宿主节点成功渲染 `我在指令构造器中创建!`。
拆分外部 JS 文件、依赖参数与命名空间隔离
在实际工程中,通常将模块声明与控制器逻辑拆分到独立 JavaScript 文件中维护,例如 `myApp.js` 负责调用 `angular.module("myApp", [])` 创建模块(第二个数组参数声明当前模块依赖的其他模块名,空数组 `[]` 表示无外部依赖;若省略第二个参数则是获取已注册模块而非新建),`myCtrl.js` 负责在对应模块上注册控制器,HTML 中先引入 `angular.min.js`,再依次加载 `myApp.js` 与 `myCtrl.js`。本站离线 Chromium 实测模拟分文件注册 `sharedLib` 与依赖它的 `mainApp`,随后通过无数组参数的 `angular.module("mainApp")` 挂载 `splitCtrl` 渲染出 `Jane Smith`,并验证获取不存在模块时正确抛出异常。
使用模块组织的另一项核心价值在于保护全局命名空间:原生 JavaScript 中直接定义全局函数极易与第三方库或其他脚本发生同名覆盖,而 AngularJS 将控制器与指令函数收敛在各自模块作用域内部,不会污染 `window` 对象。本站离线实测确认注册 `myCtrl` 后 `typeof window.myCtrl` 保持为 `"undefined"`。
AngularJS 脚本库的载入位置与顺序
对于普通 HTML 应用,通常建议把 `<script>` 标签放在 `<body>` 底部,以避免脚本下载阻塞页面 HTML 解析;但在不少 AngularJS 入门示例中会看到 `angular.min.js` 放在 `<head>` 区域,原因在于页面内对 `angular.module(...)` 的调用必须在 AngularJS 库加载并初始化全局 `angular` 对象之后才能执行。若希望兼顾渲染性能,另一种常见方案是将 AngularJS 库脚本移至 `<body>` 底部,但必须确保它位于所有业务模块与控制器脚本之前。本站离线 Chromium 实测核验了 `<head>` 中先加载库再于 `<body>` 内执行模块注册的正常启动时序。
模块依赖参数 [] 说明
| 提示主题 | 核心要点 |
| angular.module 第二个参数 [] | [] 用于声明当前模块的依赖列表;传入空数组 [] 表示新建一个无外部依赖的模块,有依赖时在数组内填入被依赖模块名字符串,省略该参数则改为检索已存在的同名模块。 |
AngularJS 库载入位置提示
| 提示主题 | 核心要点 |
| 脚本加载先后顺序 | 示例通常在 <head> 载入 AngularJS 库,也可以将其放入 <body> 底部,但必须严格位于调用 angular.module() 的自定义脚本之前。 |
离线 Chromium 核验模块注册、自定义指令驼峰映射、分文件依赖及全局隔离
展开查看收起
"""Offline Playwright Chromium lab for AngularJS Ch 16: modules."""
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 Modules Lab</title>
<script>
// Minimal offline AngularJS 1.x module / controller / directive registry equivalence
window.angular = (function () {
const modules = Object.create(null);
function toKebab(name) {
return name.replace(/([A-Z])/g, "-$1").toLowerCase();
}
function module(name, requires) {
if (Array.isArray(requires)) {
const mod = {
name,
requires: requires.slice(),
controllers: Object.create(null),
directives: Object.create(null),
controller(cName, fn) { this.controllers[cName] = fn; return this; },
directive(dName, factory) { this.directives[toKebab(dName)] = factory; return this; }
};
modules[name] = mod;
return mod;
}
if (!modules[name]) throw new Error("Module not found: " + name);
return modules[name];
}
function bootstrap(root) {
const appName = root.getAttribute("ng-app");
const mod = modules[appName];
if (!mod) throw new Error("Unknown ng-app: " + appName);
const scope = Object.create(null);
const ctrlName = root.getAttribute("ng-controller");
if (ctrlName && mod.controllers[ctrlName]) {
mod.controllers[ctrlName](scope);
}
// Render custom attribute directives
for (const [attr, factory] of Object.entries(mod.directives)) {
const targets = [];
if (root.hasAttribute(attr)) targets.push(root);
root.querySelectorAll("[" + attr + "]").forEach((el) => targets.push(el));
targets.forEach((el) => {
const def = factory();
if (def && typeof def.template === "string") el.innerHTML = def.template;
});
}
// Interpolate {{ firstName + " " + lastName }}
root.querySelectorAll("[data-bind='fullname']").forEach((el) => {
el.textContent = scope.firstName + " " + scope.lastName;
});
return { mod, scope };
}
return { module, bootstrap };
})();
</script>
</head>
<body>
<div id="app-ctrl" ng-app="myApp" ng-controller="myCtrl">
<span data-bind="fullname"></span>
</div>
<div id="app-dir" ng-app="dirApp" demo-directive></div>
<div id="app-dep" ng-app="mainApp" ng-controller="splitCtrl">
<span data-bind="fullname"></span>
</div>
<script>
// Case 1: module + controller (no global controller function leaked to window)
(function () {
const app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
})();
// Case 2: module + custom directive (camelCase -> kebab-case)
(function () {
const app = angular.module("dirApp", []);
app.directive("demoDirective", function () {
return { template: "我在指令构造器中创建!" };
});
})();
// Case 3: simulated split files (myApp.js defines module with deps, myCtrl.js retrieves module without [])
(function myAppJs() {
angular.module("sharedLib", []);
angular.module("mainApp", ["sharedLib"]);
})();
(function myCtrlJs() {
angular.module("mainApp").controller("splitCtrl", function ($scope) {
$scope.firstName = "Jane";
$scope.lastName = "Smith";
});
})();
window.__bootResults = {
ctrl: angular.bootstrap(document.getElementById("app-ctrl")),
dir: angular.bootstrap(document.getElementById("app-dir")),
dep: angular.bootstrap(document.getElementById("app-dep"))
};
</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: Module creation, controller rendering, and global namespace isolation
actual1 = page.evaluate("""() => ({
rendered: document.querySelector("#app-ctrl [data-bind='fullname']").textContent,
requires: window.__bootResults.ctrl.mod.requires,
globalMyCtrlType: typeof window.myCtrl,
angularLoadedInHead: document.head.querySelectorAll("script").length === 1
})""")
expected1 = {
"rendered": "John Doe",
"requires": [],
"globalMyCtrlType": "undefined",
"angularLoadedInHead": True,
}
cases.append({"name": "module_controller_and_namespace_isolation", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})
# Case 2: Custom directive camelCase-to-kebab-case registration
actual2 = {
"directive_text": page.text_content("#app-dir"),
"registered_attr": page.evaluate("Object.keys(window.__bootResults.dir.mod.directives)"),
}
expected2 = {
"directive_text": "我在指令构造器中创建!",
"registered_attr": ["demo-directive"],
}
cases.append({"name": "module_custom_directive_normalization", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})
# Case 3: Split file module declaration vs getter & dependency array
actual3 = page.evaluate("""() => ({
rendered: document.querySelector("#app-dep [data-bind='fullname']").textContent,
dependencies: window.__bootResults.dep.mod.requires,
missingModuleThrows: (() => {
try { angular.module("doesNotExist"); return false; }
catch (e) { return e.message.includes("Module not found"); }
})()
})""")
expected3 = {
"rendered": "Jane Smith",
"dependencies": ["sharedLib"],
"missingModuleThrows": True,
}
cases.append({"name": "module_split_files_and_dependencies", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
传入数组参数 [] 会创建(或覆盖重建)名为 myApp 的新模块并声明依赖,省略第二个参数则是获取已存在的 myApp 模块引用;用模块封装控制器可将函数限定在模块容器内,防止污染全局 window 命名空间并避免脚本间命名冲突。