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

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?

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.

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.

I use multiple controllers when my page has got multiple pop-ups with complex functionality and i want separate controllers for them so that logic behind each-pop is in its own controller.
Similarly, I create separate controllers for sidebars and header and footers on the same page.
These are few examples which comes in my mind when using multiple controllers on same page makes sense.
But as others have mentioned, you should use providers and services/factory for splitting your code.

Related

Should I have more angular services or controllers?

I am developing an angular web game where I have a bunch of quests that use a single html template for the view. The problem I have is how to organize the Angular code.
Should I have only one controller (which will hold the non-quest-specific logic) and uses a bunch of services (one for each quest-specific logic)? The controller would probably have a big if/else block to use the right service for the chosen quest.
Or should I have one controller for each quest? That way we can use fewer services overall and share them among the various controllers for the quests.
Which one makes more sense and would potentially have the fewest code duplication? Could there be a better alternative to both?
I just suggest you to go for a controller per unit and build the services thinking as elements that you can share between controllers structuring them as functional independent shareable elements.
Quest 1 = controller 1 -> inject all services needed for that quest
Quest 2 = controller 2 -> inject all services needed for this one
.......
You can't share code between controllers. If you want to have less duplicated code you should create services so you can share code between them and the controllers.
A good description of angular controllers vs. angular services can be found in an earlier post
I would recommend using a controller for each quest. Inject services into each controller that are relevant to that particular quest. Although you'll still need to write services to share that data/logic with the controller, you can avoid the unnecessary service injections as well as that massive if/esle block

AngularJs controller and directive purpose, the right way?

I've been reading up a more in depth about angularjs directive and controller, what should be in one and the other. The situation is this, I have multiple people with their types -> policemen, medicine, lawyers ... etc. inside the admin panel app, where the admin can manage them. In one section the admin can create, edit, delete them. The current versions controller does almost all the work: UI (bringing up the right form, hiding the other forms...), and logic (deleting, creating, updating methods for each person type). As I understand this is not good, because the controller does multiple things (no single responsibility). And even further the controller should only bind values to scope.
But does that mean, that I should only pull all the people (inside controller) and pass it some master directive which will manage it all? Or should their be more directives inside directives to divide the responsibility?
And if so, the controller will have to use the same service as the directive/directives. Controller for pulling people from back-end) and the directive/directives (for creating/updating/deleting) is this DRY?
Without code it's hard to give a precise answer, but the general idea when working with angular is this:
Controller: The controller is responsible for keeping the views up to date with all the changes that are happening throughout your app. This means that it should not contain the business logic, this logic should instead be separated into small services. Each handling different parts of the logic for your app.
Service: As stated above, a service should contain your business logic. Meaning that heavy calculations, manipulations etc. should be put into a service. Since services are singletons you can easily inject this service anywhere and re-use the logic within it, something you cannot do if you've put your logic inside a controller.
Directives: Like controllers, directives shouldn't have any business logic in them. Directives are only there to create re-useable functionality as well as giving you a place to handle direct DOM changes. DOM changes should never be done anywhere but from within a directive.
To answer this:
And if so, the controller will have to use the same service as the directive/directives. Controller for pulling people from back-end) and the directive/directives (for creating/updating/deleting) is this DRY?
If you have the data bound to a controller, you should not necessarily need a directive to handle the CRUD operations. Since the data is bound to the controller, you can easily create a template which reacts to the data changes automatically using ng-repeat, ng-if and so on.

why / when to use multiple controller - Angularjs

I started working with AngularJs recently.
Looking to understand the reason for using multiple controller, I found different site explaning how to use multiple controller (AngularJS site). But what I'm actually looking for is a rationnal for using multiple controller.
So my question is : Why or when should we use multiple controller in a project? and the subquestion that is tied to this question: is it a good pratice to use multiple controller in an Angular project.
That's also an MVC question as angular extends this pattern. In Apple's View Controller Programming Guide for iOS, it says :
Every view is controlled by only one view controller.
So the idea in MVC pattern is to separate views. By having 1 Controller per View it makes it easier to achieve this. it simplifies the organization of controllers that serve one module. You do not suffer from code smells.
Also, it is important for routing issues in app.js for angular case. It clarifies structure for other developers that will have look at project. Using testacular in angularjs, unit testing is great, having multiple controllers makes unit testing easier.
Edit :
You would also most likely need more controllers for further functionalities. For example a Auth Controller where users can create new accounts. In addition to this you need a superadmin view where you can edit the resources with higher privileges. In such a case it is quite common to have separate controller. Scope and security issues has to change.
It is just a very good pratice to use 1 controller per 1 view. So for example you should have seperate controller for /home view, another one for /gallery, and another /contact.
It forces you as a developer to organise your code, so that you can take advantage of using services, filters etc.
Also it is easier to write unit tests because you can see what is covered and what is not.

AngularJS data model architecture approach

I'm new to AngularJS and having a hard time wrapping my head around the conceptual model.
Let's say I want to have an object hierarchy to model a stash repository: Projects contain Repositories contain Tags. Do I create one app, one module and multiple controllers? (Can a module have multiple controllers?) Separate app per object type? Separate module per object type?
All the various data types will be populated by making REST API queries. Read-only for now. Does that change things?
Also, why are they called controllers? They seem to be models. As far as I can tell the controller is actually the AngularJS plumbing.
Here is my rather simple explanation:
A module is just simply a container for all the bits and pieces of your app (services, controllers, directives, filters etc).
Your application may contain different modules - some that you wrote and other third party ones, such as ngGrid for example.
You define a module like this:
var myAppModule = angular.module('myApp', []);
A controller is where the business logic of your application resides. The controller may handle the model, but it is not the model.
The AngularJS documentation for controllers states:
Use controllers to:
Set up the initial state of the $scope object. Add behavior to the
$scope object.
I break up my controllers in to the logical functions that they are supposed to handle. For example, I've written an app to help with combat tracking in a tabletop RPG. I have a controller that handles martial combat and another that handles magick. I also have another controller that helps with the characters. All these controllers are part of my combat app.
I only have one service that is responsible for querying a REST API to retrieve stats and results from a database.
The AngularJS documentation has improved a lot recently and I would recommend reading through it to give you a rough idea of how things work together!
In your example, I'd have a separate controller for each of Projects, Repositories and Tags. I'd have a service to query your datatypes. These would be grouped as part of one module/app.

Angularjs - Best practices for controllers / routing / partials

So I am just starting out with angularjs and web development in general and had a few questions regarding the best practices. Some of my questions are actually more related to web development in general.
1) When to use partials and when to use a different page instead. E.g Is is good to embed about.html as a partial in index.html or have a separate page?
2) What is the best way to share data between controllers? Right now I am using query parameters in the route.
3) Should I be using one controller for multiple partials?
Thanks!
Angular is a single page app framework, so you only want to use one html 'page' in most cases. There may be exceptions but unless your project is very large you won't need to use more than one.
Services are the recommended way of doing this. Services return a singleton object, and you can inject references to them using angular's dependency injection. It keeps everything modular, too. Query params are definitely not what you want to use. For calling events between controllers you might also use $scope.$broadcast().
Potentially, you might have an overall AppController for example that encompasses elements that have their own controllers (in their own directives, or using ng-controller). On the subject of directives, remember to use them to bundle re-usable components up. Directives have their own templates and controllers, and using them makes your code much more modular and easier to maintain/test.

Resources