0
votes

I've been thinking about the concept of controller in the MVC pattern, but there's something i would like to discuss, should we create a controller per entity (let's say Product) or per view when using angularJS (since angularJS follows the singleton concept) or is it right to have a controller for all the views related to "products" for example?

I'll give a situation:

Let's say we have a module called purchases and under that module we've got three submodules: products, suppliers, & stock-moves, each submodule has views for the CRUD operations, let's say that under products we have: list-products.view.html, create-product.view.html, edit-product.view.html; what would be the best approach for the controllers? a single controller per view, or a controller for all views?

Thanks for your help

2

2 Answers

2
votes

I always go for a controller per view, regardless of whether that results in having multiple controllers per entity or not. The reasoning for this is simple. Whenever a view is malfunctioning I want to look at the smallest subset of code to figure out what went wrong.

Also, if you think about it the controller's job is to respond to commands from view and communicate model changes to views. So, in essence your controller is not supposed to manage entities but it's used to manage your view.

This approach has served me in 98% of the cases without any issues. Obviously, in software there are no absolute answers so there might be some scenarios where a per entity controller might fit in more seamlessly. But for me, from a practical as well as a philosophical perspective a controller per view makes more sense.

0
votes

I usually use one controller and route for each view, this is the most used approach. It helps to logically structure the application especially when it begins to grow.

There is another case when I use multiple controllers per view to govern different areas of the view. In such a scenario each controller manages a fragment of the overall page.