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

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

问题描述

我有一个单页应用程序,它有一个根模块,其中包含大约 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.

例如这个控制器:

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-app="root" 启动我的应用程序.一切都共享范围这是否正常,或者我的设置有问题?

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.

推荐答案

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

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

这是关于范围的文档:

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.

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

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