AngularJS Scope(作用域)
阐明 $scope 作为视图与控制器纽带的 MVC 定位、多作用域与 ng-repeat 子作用域隔离机制,以及 $rootScope 原型链共享与属性遮蔽现象。
学完这一章,你能够
- 阐明 $scope 作为视图与控制器纽带的 MVC 定位、多作用域与 ng-repeat 子作用域隔离机制,以及 $rootScope 原型链共享与属性遮蔽现象。
Scope 的定位与控制器传参用法
Scope(作用域)是连接 HTML 视图与 JavaScript 控制器的核心纽带,本质上是一个可挂载数据属性与方法的 JavaScript 对象。定义控制器时将 `$scope` 作为参数注入并在其上赋值(例如 `$scope.carname = "Volvo"`),视图层无需书写 `$scope.` 前缀,直接用 `{{carname}}` 即可读取该属性。本站离线 Chromium 实测验证 `{{carname}}` 准确渲染为 `"Volvo"`。
MVC 结构中的双向联动与方法调用
AngularJS 应用遵循经典 MVC 划分:View(视图)是 HTML 模板,Model(模型)即当前视图可用的作用域数据,Controller(控制器)则是负责初始化或变更模型属性与行为的 JavaScript 函数。由于 `$scope` 同时扮演模型容器,用户修改视图中的输入框或通过 `ng-click` 调用 `$scope` 方法时,模型与视图会自动联动。本站实测:初始 `$scope.name = "BlueSky"`,点击按钮调用 `sayHello()` 后标题变为 `"Hello BlueSky!"`,改输入 `"Angular"` 并再次点击即更新为 `"Hello Angular!"`。
多作用域边界、ng-repeat 子作用域与 $rootScope
在多区块页面中,DOM 树会形成嵌套的作用域层级,明确当前节点所处作用域至关重要。以 `ng-repeat="x in names"` 为例,AngularJS 会为数组中的每一项通过原型继承创建一个独立子作用域,使每个 `<li>` 各自持有专属的循环变量 `x` 而不污染父级控制器作用域。本站实测对 `["Emil", "Tobias", "Linus"]` 生成了 3 个 `<li>` 与 3 个继承自父作用域的子作用域,且父作用域自身不存在 `x` 属性(`hasOwnProperty('x') === false`)。
每个 AngularJS 应用都拥有唯一顶层根作用域 `$rootScope`,覆盖 `ng-app` 所辖全部元素,可作为不同控制器之间共享数据的桥梁。将 `$rootScope` 注入控制器并写入 `$rootScope.lastname = "Refsnes"` 后,子作用域与同级其他控制器均可通过原型链读取 `{{lastname}}`。本站实测:`familyCtrl` 下的列表渲染出 `["Emil Refsnes", "Tobias Refsnes", "Linus Refsnes"]`,同级 `siblingCtrl` 同样读到 `"Refsnes"`;当在子作用域直接赋值同名原始值属性时,会在子作用域创建局部遮蔽属性而保持 `$rootScope.lastname` 原值不变。
验证 $scope 属性映射、ng-click 联动、ng-repeat 子作用域隔离及 $rootScope 继承
展开查看收起
"""Offline Playwright Chromium lab for AngularJS Ch 06 (scopes)."""
import json
from playwright.sync_api import sync_playwright
HTML_PAGE = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS Scopes Offline Lab</title></head>
<body>
<div id="sec-basic" ng-app="app1" ng-controller="carCtrl">
<h1 id="car-out">{{carname}}</h1>
</div>
<div id="sec-mvc" ng-app="app2" ng-controller="greetCtrl">
<input id="mvc-inp" ng-model="name">
<h1 id="mvc-greeting">{{greeting}}</h1>
<button id="mvc-btn" ng-click="sayHello()">点我</button>
</div>
<div id="sec-repeat" ng-app="app3" ng-controller="listCtrl">
<ul id="repeat-ul"><li ng-repeat="x in names">{{x}}</li></ul>
</div>
<div id="sec-root" ng-app="app4">
<div id="ctrl-a" ng-controller="familyCtrl">
<h1 id="root-title">{{lastname}} 家族成员:</h1>
<ul id="root-ul"><li ng-repeat="x in names">{{x}} {{lastname}}</li></ul>
</div>
<div id="ctrl-b" ng-controller="siblingCtrl">
<p id="sibling-last">{{lastname}}</p>
<p id="sibling-shadow">{{ownTag}}</p>
</div>
</div>
<script>
(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];
}
};
angular.module("app1", []).controller("carCtrl", function ($scope) {
$scope.carname = "Volvo";
});
angular.module("app2", []).controller("greetCtrl", function ($scope) {
$scope.name = "BlueSky";
$scope.sayHello = function () {
$scope.greeting = "Hello " + $scope.name + "!";
};
});
angular.module("app3", []).controller("listCtrl", function ($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
const app4 = angular.module("app4", []);
app4.controller("familyCtrl", function ($scope, $rootScope) {
$scope.names = ["Emil", "Tobias", "Linus"];
$rootScope.lastname = "Refsnes";
});
app4.controller("siblingCtrl", function ($scope) {
$scope.ownTag = "inherited:" + $scope.lastname;
});
function evalExpr(expr, scope) {
try {
const v = new Function("scope", "with(scope){ return (" + expr + "); }")(scope);
return v === undefined || v === null ? "" : String(v);
} catch (_) {
return "";
}
}
function bindElementTree(container, scope) {
const repeatEls = Array.from(container.querySelectorAll("[ng-repeat]"));
const childScopes = [];
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;
childScopes.push(cScope);
const clone = cloneBase.cloneNode(true);
bindElementTree(clone, cScope);
parent.appendChild(clone);
}
}
container.__childScopes = childScopes;
const textBindings = [];
const walker = document.createTreeWalker(container, 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));
}
}
container.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();
});
});
container.querySelectorAll("[ng-click]").forEach((el) => {
const callExpr = el.getAttribute("ng-click");
el.addEventListener("click", () => {
new Function("scope", "with(scope){ " + callExpr + "; }")(scope);
render();
});
});
render();
}
window.__scopes = {};
document.querySelectorAll("[ng-app]").forEach((appEl) => {
const appName = appEl.getAttribute("ng-app");
const mod = modules[appName];
const rootScope = {};
window.__scopes[appName] = { rootScope, controllers: {} };
const ctrlEls = appEl.hasAttribute("ng-controller")
? [appEl]
: Array.from(appEl.querySelectorAll("[ng-controller]"));
for (const cEl of ctrlEls) {
const cname = cEl.getAttribute("ng-controller");
const childScope = Object.create(rootScope);
mod._ctrls[cname](childScope, rootScope);
window.__scopes[appName].controllers[cname] = childScope;
bindElementTree(cEl, childScope);
}
});
})();
</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: $scope property rendered without $scope prefix
actual_1 = {"carname": page.locator("#car-out").text_content()}
expected_1 = {"carname": "Volvo"}
cases.append({
"name": "scope_controller_to_view_binding",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: MVC two-way update + ng-click method
before_click = page.locator("#mvc-greeting").text_content()
page.click("#mvc-btn")
first_click = page.locator("#mvc-greeting").text_content()
page.fill("#mvc-inp", "Angular")
page.click("#mvc-btn")
second_click = page.locator("#mvc-greeting").text_content()
actual_2 = {
"before_click": before_click,
"after_first_click": first_click,
"after_edit_and_click": second_click,
}
expected_2 = {
"before_click": "",
"after_first_click": "Hello BlueSky!",
"after_edit_and_click": "Hello Angular!",
}
cases.append({
"name": "scope_mvc_two_way_and_ng_click",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: ng-repeat creates isolated child scope per item
repeat_check = page.evaluate("""() => {
const parent = window.__scopes.app3.controllers.listCtrl;
const ul = document.getElementById('sec-repeat');
return {
items: Array.from(document.querySelectorAll('#repeat-ul li')).map(el => el.textContent),
child_scope_count: ul.__childScopes.length,
parent_has_own_x: Object.prototype.hasOwnProperty.call(parent, 'x'),
child_inherits_parent: ul.__childScopes.every(cs => Object.getPrototypeOf(cs) === parent)
};
}""")
expected_3 = {
"items": ["Emil", "Tobias", "Linus"],
"child_scope_count": 3,
"parent_has_own_x": False,
"child_inherits_parent": True,
}
cases.append({
"name": "scope_ng_repeat_child_scopes",
"expected": expected_3,
"actual": repeat_check,
"passed": repeat_check == expected_3,
})
# Case 4: $rootScope shared across controllers via prototype inheritance
root_check = page.evaluate("""() => {
const root = window.__scopes.app4.rootScope;
const sib = window.__scopes.app4.controllers.siblingCtrl;
sib.lastname = "LocalOverride";
return {
heading: document.getElementById('root-title').textContent,
family_items: Array.from(document.querySelectorAll('#root-ul li')).map(el => el.textContent),
sibling_rendered: document.getElementById('sibling-last').textContent,
sibling_tag: document.getElementById('sibling-shadow').textContent,
root_unchanged_after_child_shadow: root.lastname === "Refsnes" && sib.lastname === "LocalOverride"
};
}""")
expected_4 = {
"heading": "Refsnes 家族成员:",
"family_items": ["Emil Refsnes", "Tobias Refsnes", "Linus Refsnes"],
"sibling_rendered": "Refsnes",
"sibling_tag": "inherited:Refsnes",
"root_unchanged_after_child_shadow": True,
}
cases.append({
"name": "root_scope_shared_across_controllers",
"expected": expected_4,
"actual": root_check,
"passed": root_check == expected_4,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为子作用域基于 JavaScript 原型链继承 $rootScope,读取时沿原型链向上查找,但写入原始值会在子作用域自身新建同名属性造成遮蔽;工程中应优先通过服务(Service)共享状态,或使用包含点号的引用对象属性(如 shared.lastname)。