问题
I have a single page application, which has a root module with about 5 seperate smaller modules.
var rootModule = angular.module('root', ["firstModule", "secondModule", "thirdModule"])
Each module has directives and controllers. Today I discovered that I can access other module and controller scope from all other modules and controllers.
So for example this controller:
thirdModule.controller('ThirdController', ['$scope', function ($scope) {
alert($scope.title);
}
And in this controller I alert the variable and it works.
firstModule.controller('FirstController', ['$scope', function ($scope) {
$scope.title = "Hello"
}
So basically I initiate my application with ng-app="root"
. Is this normal that everything has shared scope, or I have something wrong with my setup?
I thought modules give me code seperation and controllers are singletons with new scope.
回答1:
Each module (directive) will need its own (child) scope — either an isolate scope scope: {}
or a new scope scope: true
to prevent the cross scope issue.
Examples:
// Create new scope:
var scope = $rootScope.$new(); // only one root per application
scope.salutation = 'Hello';
scope.name = 'World';
Inherit, create a new child scope in the parent scope
var parentScope = $rootScope; // one root per application
var child = parentScope.$new();
parentScope.salutation = "Hello";
child.name = "World";
Here is the documentation on scope:
http://docs.angularjs.org/api/ng.$rootScope.Scope
Here is some documentation on the scope/inheritance:
https://github.com/angular/angular.js/wiki/Understanding-Scopes
In fairness, I would NOT consider myself an "angularjs" expert at this point.
回答2:
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
来源:https://stackoverflow.com/questions/18980337/angular-scope-is-shared-for-all-modules-and-controllers