2

我有一个单页应用程序,它有一个带有大约 5 个单独的较小模块的根模块。

var rootModule = angular.module('root', ["firstModule", "secondModule", "thirdModule"])

每个模块都有指令和控制器。今天我发现我可以从所有其他模块和控制器访问其他模块和控制器范围。

例如这个控制器:

thirdModule.controller('ThirdController', ['$scope', function ($scope) {
   alert($scope.title);
}

在这个控制器中,我提醒变量并且它可以工作。

firstModule.controller('FirstController', ['$scope', function ($scope) {
   $scope.title = "Hello"
}

所以基本上我用ng-app="root". 一切都共享范围是正常的,还是我的设置有问题?

我认为模块给了我代码分离,控制器是具有新范围的单例。

4

2 回答 2

3

Without seeing the HTML it is hard, but I would guess that you controllers are nested in the html? Something like:

<div ng-controller="FirstController">
  <div ng-controller="ThirdController">
  </div>
</div>

Controllers use prototypical inheritance when nested. The child inherits from the parent and can access its scope. So ThirdController will in this case be able to access the scope from FirstController. If they where siblings instead of nested then ThirdController would not have access to FirstController.

This is very useful, but there are a few gotchas here that you can fall into if you don't know how this kind of inheritance works, especially when it comes to the difference between inheriting an object and inheriting a primitive (this confused me to no end when I started with Angular).

I can write some more about it if you want and this was indeed what was going on, or you can look at this answer for more about prototypical inheritance: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

This video also demonstrates the difference between objects and primitives when inheriting: http://www.youtube.com/watch?v=DTx23w4z6Kc&feature=player_embedded

于 2013-09-24T14:04:51.277 回答
2

每个模块(指令)都需要自己的(子)范围——隔离范围scope: {}或新范围scope: true以防止跨范围问题。

例子:

// Create new scope:
var scope = $rootScope.$new();  // only one root per application
scope.salutation = 'Hello';
scope.name = 'World';

继承,在父作用域中新建一个子作用域

var parentScope = $rootScope;  // one root per application
var child = parentScope.$new();

parentScope.salutation = "Hello";
child.name = "World";

这是有关范围的文档:

http://docs.angularjs.org/api/ng.$ro​​otScope.Scope

以下是有关范围/继承的一些文档:

https://github.com/angular/angular.js/wiki/Understanding-Scopes

公平地说,此时我不会认为自己是“angularjs”专家。

于 2013-09-25T16:50:27.333 回答