我有一个单页应用程序,它有一个根模块和大约 5 个独立的较小模块。
var rootModule = angular.module('root', ["firstModule", "secondModule", "thirdModule"])
每个模块都有指令和 Controller 。今天我发现我可以从所有其他模块和 Controller 访问其他模块和 Controller 范围。
例如这个 Controller :
thirdModule.controller('ThirdController', ['$scope', function ($scope) {
alert($scope.title);
}
在这个 Controller 中,我警告变量并且它起作用了。
firstModule.controller('FirstController', ['$scope', function ($scope) {
$scope.title = "Hello"
}
所以基本上我用 ng-app="root"
启动我的应用程序。一切都有共享范围,这正常吗?还是我的设置有问题?
我认为模块为我提供了代码分离, Controller 是具有新作用域的单例。
最佳答案
如果没有看到 HTML,这很难,但我猜你的 Controller 是嵌套在 html 中的?像这样的东西:
<div ng-controller="FirstController">
<div ng-controller="ThirdController">
</div>
</div>
Controller 在嵌套时使用原型(prototype)继承。子级继承自父级并可以访问其范围。因此,在这种情况下,ThirdController 将能够从 FirstController 访问范围。如果它们是兄弟而不是嵌套,那么 ThirdController 将无法访问 FirstController。
这非常有用,但是如果您不知道这种继承是如何工作的,那么您可能会陷入一些陷阱,特别是当涉及到继承对象和继承基元之间的区别时(这当我开始使用 Angular 时,这让我感到非常困惑)。
如果您愿意,我可以写更多相关内容,这确实是正在发生的事情,或者您可以查看此答案以了解有关原型(prototype)继承的更多信息:What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
该视频还演示了继承时对象和基元之间的区别:http://www.youtube.com/watch?v=DTx23w4z6Kc&feature=player_embedded
关于javascript - 所有模块和 Controller 共享 Angular 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980337/