AngularJS 控制器
讲解 ng-controller 指令、控制器属性与方法定义,以及将控制器拆分到外部 JavaScript 文件(personController.js、namesController.js)并在本地同源加载的组织方式。
学完这一章,你能够
- 讲解 ng-controller 指令、控制器属性与方法定义,以及将控制器拆分到外部 JavaScript 文件(personController.js、namesController.js)并在本地同源加载的组织方式。
控制器职责与 ng-controller 解析
AngularJS 控制器用于管理应用数据与业务逻辑,本质上是由标准 JavaScript 构造函数创建的常规对象。页面通过 `ng-app` 定义应用容器,再由 `ng-controller="myCtrl"` 指定挂载到该容器的控制器函数。AngularJS 实例化控制器时会传入 `$scope` 应用对象来承载模型变量与方法:控制器在 `$scope` 上创建 `firstName` 与 `lastName` 两个属性,模板通过 `ng-model` 将输入框双向绑定到这两个属性。本站离线 Chromium 实测:初始渲染 `"John Doe"`,将两输入框改为 `"Linus"` 与 `"Torvalds"` 后即时刷新为 `"Linus Torvalds"`。
在控制器作用域上定义方法
控制器不仅能挂载静态数据属性,还能挂载计算或交互方法。例如在 `personCtrl` 中定义 `$scope.fullName = function() { return $scope.firstName + " " + $scope.lastName; }`,模板里即可直接调用 `{{fullName()}}`。本站离线实测:初始输出 `"John Doe"`,将 `firstName` 改为 `"Ada"` 后 `fullName()` 随脏检查重新求值并输出 `"Ada Doe"`。
将控制器拆分到外部脚本文件
中大型单页应用不应把全部控制器逻辑堆砌在内联 `<script>` 标签中,而应按功能模块拆分到独立外部文件。例如把人员控制器代码保存为 `personController.js` 并通过 `<script src="personController.js"></script>` 引入,即可保持 HTML 模板精简清晰。本站通过本地回环静态服务加载外部 `personController.js` 实测:初始输出 `"John Doe"`,改填 `"Alan"` 与 `"Turing"` 后同步更新为 `"Alan Turing"`。
同理,可将对象数组数据源封装到独立的 `namesController.js` 文件,在其中注册 `namesCtrl` 并将包含 3 条 `{name, country}` 记录的数组挂到 `$scope.names`,再在 HTML 中配合 `ng-repeat="x in names"` 渲染列表。本站通过本地回环加载外部 `namesController.js` 实测,准确输出 3 条记录 `["Jani, Norway", "Hege, Sweden", "Kai, Denmark"]`。
验证控制器属性绑定、fullName() 方法重算及外部控制器脚本加载
"""Offline Playwright Chromium lab for AngularJS Ch 07 (controllers)."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright
RUNTIME_JS = r"""
(function () {
const modules = {};
window.angular = {
module(name, deps) {
if (deps) {
const mod = { _ctrls: {} };
mod.controller = function (cname, fn) {
mod._ctrls[cname] = fn;
return mod;
};
modules[name] = mod;
return mod;
}
return modules[name];
}
};
function evalExpr(expr, scope) {
const v = new Function("scope", "with(scope){ return (" + expr + "); }")(scope);
return v === undefined || v === null ? "" : String(v);
}
function renderTree(root, scope) {
const repeatEls = Array.from(root.querySelectorAll("[ng-repeat]"));
for (const tplEl of repeatEls) {
const m = tplEl.getAttribute("ng-repeat").trim().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 cScope = Object.create(scope);
cScope[itemVar] = item;
const clone = cloneBase.cloneNode(true);
renderTree(clone, cScope);
parent.appendChild(clone);
}
}
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) => evalExpr(ex.trim(), scope));
}
}
root.querySelectorAll("[ng-model]").forEach((el) => {
const prop = el.getAttribute("ng-model");
if (scope[prop] !== undefined) el.value = scope[prop];
el.addEventListener("input", () => {
scope[prop] = el.value;
render();
});
});
render();
}
window.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll("[ng-app]").forEach((root) => {
const appName = root.getAttribute("ng-app");
const ctrlName = root.getAttribute("ng-controller");
const scope = {};
if (modules[appName] && modules[appName]._ctrls[ctrlName]) {
modules[appName]._ctrls[ctrlName](scope);
}
renderTree(root, scope);
});
});
})();
"""
PERSON_CTRL_JS = """
angular.module('extPersonApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
"""
NAMES_CTRL_JS = """
angular.module('extNamesApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{ name: 'Jani', country: 'Norway' },
{ name: 'Hege', country: 'Sweden' },
{ name: 'Kai', country: 'Denmark' }
];
});
"""
INDEX_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS Controllers Offline Lab</title>
<script src="/mini-angular.js"></script>
</head>
<body>
<div id="sec-basic" ng-app="basicApp" ng-controller="myCtrl">
<input id="b-first" type="text" ng-model="firstName">
<input id="b-last" type="text" ng-model="lastName">
<p id="b-out">{{firstName + " " + lastName}}</p>
</div>
<div id="sec-method" ng-app="methodApp" ng-controller="personMethodCtrl">
<input id="m-first" type="text" ng-model="firstName">
<input id="m-last" type="text" ng-model="lastName">
<p id="m-out">{{fullName()}}</p>
</div>
<div id="sec-ext-person" ng-app="extPersonApp" ng-controller="personCtrl">
<input id="ep-first" type="text" ng-model="firstName">
<input id="ep-last" type="text" ng-model="lastName">
<p id="ep-out">{{firstName + " " + lastName}}</p>
</div>
<div id="sec-ext-names" ng-app="extNamesApp" ng-controller="namesCtrl">
<ul id="en-ul"><li ng-repeat="x in names">{{ x.name + ', ' + x.country }}</li></ul>
</div>
<script>
angular.module('basicApp', []).controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
angular.module('methodApp', []).controller('personMethodCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
<script src="/personController.js"></script>
<script src="/namesController.js"></script>
</body>
</html>
"""
ROUTES = {
"/": ("text/html; charset=utf-8", INDEX_HTML),
"/mini-angular.js": ("application/javascript; charset=utf-8", RUNTIME_JS),
"/personController.js": ("application/javascript; charset=utf-8", PERSON_CTRL_JS),
"/namesController.js": ("application/javascript; charset=utf-8", NAMES_CTRL_JS),
}
class LocalHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path in ROUTES:
ctype, body = ROUTES[self.path]
data = body.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
pass
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), LocalHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/", wait_until="load")
# Case 1: Controller properties & two-way binding
b_init = page.locator("#b-out").text_content()
page.fill("#b-first", "Linus")
page.fill("#b-last", "Torvalds")
b_upd = page.locator("#b-out").text_content()
actual_1 = {"initial": b_init, "updated": b_upd}
expected_1 = {"initial": "John Doe", "updated": "Linus Torvalds"}
cases.append({
"name": "controller_properties_and_two_way",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Controller method fullName()
m_init = page.locator("#m-out").text_content()
page.fill("#m-first", "Ada")
m_upd = page.locator("#m-out").text_content()
actual_2 = {"initial": m_init, "after_first_edit": m_upd}
expected_2 = {"initial": "John Doe", "after_first_edit": "Ada Doe"}
cases.append({
"name": "controller_method_full_name",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: External personController.js script
ep_init = page.locator("#ep-out").text_content()
page.fill("#ep-first", "Alan")
page.fill("#ep-last", "Turing")
ep_upd = page.locator("#ep-out").text_content()
actual_3 = {"initial": ep_init, "updated": ep_upd}
expected_3 = {"initial": "John Doe", "updated": "Alan Turing"}
cases.append({
"name": "external_person_controller_script",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: External namesController.js + ng-repeat
items = page.locator("#en-ul li").all_text_contents()
actual_4 = {"count": len(items), "items": items}
expected_4 = {
"count": 3,
"items": ["Jani, Norway", "Hege, Sweden", "Kai, Denmark"],
}
cases.append({
"name": "external_names_controller_ng_repeat",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 myCtrl 从 John Doe 更新为 Linus Torvalds;personCtrl 方法 fullName() 动态变为 Ada Doe;本地回环加载 personController.js 与 namesController.js 均成功注册并渲染 3 条人员记录。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:b4473a188a20b53c8f368020e858db43eacaf0bca4c897e7d3f2c50231e4a071
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:cfad83c0f97fdc500190de30a05968833e2e8ef846db9465dc9fb490b52df8ee
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 AngularJS 中把控制器拆成外部文件时,为什么外部控制器脚本必须在引入 angular.min.js 之后加载?若多个控制器共用同一模块,第二次调用 angular.module('myApp', []) 会产生什么后果?
展开参考解答
因为外部文件顶层会调用全局 angular.module(...),若放在框架脚本之前会触发 ReferenceError;另外传入第二个依赖数组参数 [] 会重新创建并覆盖同名模块导致此前注册的控制器丢失,追加控制器应使用无第二参数的 getter 形式 angular.module('myApp')。