角范围为所有模块和控制器共享 [英] Angular scope is shared for all modules and controllers

查看:76
本文介绍了角范围为所有模块和控制器共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单页的应用程序,其中有大约5独立小模块根模块。

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"
}

所以基本上我开始我的应用程序NG-应用=根。这是正常的,一切都已经共享范围,或者我有什么毛病我的设置?

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?

我以为模块给我code分离和控制器与新天地单身。

I thought modules give me code seperation and controllers are singletons with new scope.

推荐答案

每个模块(指令)将需要自己的(孩子)范围 - 要么是分离范围范围:{} 或一个新的作用域范围:真正的来prevent跨范围问题

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.

例如:

// 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.$ro​​otScope。适用范围

下面是范围/继承一些文档:

Here is some documentation on the scope/inheritance:

https://github.com/angular/angular.js/wiki/了解-作用域

在公平,我不认为自己在这一点上是angularjs专家。

In fairness, I would NOT consider myself an "angularjs" expert at this point.

这篇关于角范围为所有模块和控制器共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆