When should multiple controllers be used in the same page in angularjs?

时间:2015-08-07 02:13:40

标签: angularjs angularjs-controller

I would like to know when does it make sense to use multiple controllers on the same page in angularjs. Also, when should one think about separating a controller into multiple controllers?

3 个答案:

答案 0 :(得分:0)

You should largely have your functionality in providers (services or factories typically) and your controllers should have very little in them aside from getting the providers injected (and exposing models and functions for use in the view) and possibly some view specific functionality (configuration for directives used only in one place etc.). You can have multiple controllers on the page if you decide to build the views within a page to be portable.

If you have one controller that shares the functionality needed for disparate parts of a page and later decide to move one part of the view to another route/state/view then you'll need to piece apart the controller. I don't think there are any hard rules really but if your controller is more than 100 lines you're probably making it responsible for too much and should "promote" some things to be handled by providers and/or start splitting things up a bit more.

答案 1 :(得分:0)

The answer would be dependent on your page requirement. Having multiple controllers can easily be done.. But issues pop-up when you wanted to have page flows.

Controllers are just a part of AngularJS.. Usage of services, factories and filters is a recommended way of splitting your code along with controllers. If multiple controllers per page becomes imperative.. try utilizing directives. Also consider using Views provider by UI router.

答案 2 :(得分:0)

当我的页面有多个具有复杂功能的弹出窗口时,我使用多个控制器,并且我需要单独的控制器,以便每个pop后面的逻辑位于自己的控制器中。

同样,我在同一页面上为侧边栏和页眉和页脚创建了单独的控制器。 在同一页面上使用多个控制器时,我会想到这几个例子。

但正如其他人所提到的,你应该使用提供者和服务/工厂来分割你的代码。