javascript - 所有模块和 Controller 共享 Angular 范围

标签 javascript angularjs angularjs-directive angularjs-scope

我有一个单页应用程序,它有一个根模块和大约 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/

相关文章:

javascript - 如何验证 Angular 值 1 和 1.00 相同且 1.01 不同

java - 为什么 nsIScriptableInputStream 不工作?

javascript - 如何递归地将嵌套对象数组转换为平面对象数组?

javascript - 按钮上的 Angular 单击 ctrl 外部,传递按钮 id

javascript - 在 ng-view 之外更新 HTML 元素

javascript - 使用 Angular Directive(指令)的聊天应用程序的可扩展文本区域字段

javascript - 如何使用 AngularJS $rootScope?

javascript - 使用 JSON 值实现数组交集

javascript - ionic View 中缺少标题

unit-testing - 测试使用模板的指令