11

I just started to use AngularJS, so I'm not an expert.

I have a div that represent the right area of my html view. In that div I have a controller, i.e.

<div class="rightContainer" ng-controller="rightContainerCtrl">...</div>

Inside that div I have a table, a search region, etc. Each region inside that div has its own controllers, it looks like this:

<div class="rightContainer" ng-controller="rightContainerCtrl">
...
   <div class="search" ng-controller="searchCtrl">...</div>
...
   <div class="table" ng-controller="tableCtrl">...</div>

 </div>

the search region for example has its own controller and it is a child of rightContainerCtrl because it needs to alter some content in the parent (rightContainerCtrl), but the rightContainer div is growing and now it's big, and contain several nested controllers.

I think that using this nested controllers it's bad in this context because all the nested controllers share the parent scope, and not all controllers needs to access all the parent scope variables, also all the controllers are "prisoners" of the rightContainerCtrl, so they are highly coupled with their parent controller.

It looks like a God object anti-pattern (God controller in this case), so I think that instead of using nested controllers I can refactor my code to eliminate the rightContainerCtrl controller and use a service instead (like in a facade design pattern), that service then will be used by the controllers instead of sharing scope variables.

but since I'm not an AngularJs expert I'm not sure if I'm right or if it's better to leave this parent controller, maybe I'm missing something, so my question is

When is better to use nested controllers (nested scopes) and when it's better to use services instead in angularjs?

4

2 回答 2

17

控制器/范围层次结构不应规定数据/模型在应用程序中的共享方式。当您想到 Angular 中的数据共享时,请考虑依赖注入。

在@shaunhusain 的回答中引用的视频中,Misko 指出范围应该是指模型,而不是模型——所以不要建模/将您的数据放入范围。您的模型/数据通常应该在服务中。

在编写 Angular 应用程序时,首先要考虑您的模型。将它们放入带有 API 的服务中,以获取/编辑/操作模型。然后设计你的观点。每个视图都应该投影/使用/操作模型的某些子集。为每个视图定义一个控制器,简单地将所需的模型子集粘合到视图上。使您的控制器尽可能薄。

rightContainerCtrl(也不建议命名控制器。控制器不应该知道演示/布局。)

于 2013-07-22T19:03:15.990 回答
7

这是 100% 的判断,应该基于几点。

使用事件会创建极其松散耦合的组件,它们实际上不需要相互了解,如果您遇到某些父控制器会减轻一堆控制器(通过服务)之间通信的需要的情况,那么它可能会更好解决方案。

但是,如果您对每个取决于服务的控制器都满意(这不是真正的问题),那么您可以使用该服务作为在控制器之间传达更改的一种方式。我已经看到大量反对单例的论点(其中服务是一种风格,注入的单例,但仍然是单例)我发现这些论点大多没有实际意义,并且通常缺乏真正优雅和简洁的解决方案。如果关于当你从 A 到 D 时如何走你不想走 B 路但他们似乎从来没有提供路 CI 的争论不休,那你就真的不明白这一点。

http://www.youtube.com/watch?v=ZhfUv0spHCY&t=30m34s

我在视频中找不到确切的点,但在最后的某个地方,他讨论了控制器与服务的使用(他还审查了双向数据绑定,这将阻止你需要污染全局范围) .

于 2013-07-22T18:04:14.027 回答