Should there be one controller to view in Angularjs?

I am from asp.net mvc background and recently started working with Angularjs. I have a simple object called Account that opens through a RESTful asp.net web api. Now I create my client side using Angular. On the client side, I have views such as create, edit, list, and drill down.

Should I create a controller for each view or should there be only one controller named `accountController 'for all CRUD operations? What is the standard practice in this scenario?

+5
source share
3 answers

Do not look at controllers in terms of "operations" such as CRUD, in this case yu "talk to a soothing API", since soothing services use HTTP verbs to display CRUD operations, for example:

 PUT, POST -> Create GET -> Read POST -> Update DELETE -> Delete 

It is good practice to create angular services and return the $ resource for later use, mapping the $ resource to your CRUD endpoints as follows:

 angular.module('app').factory('Users', ['$resource', function($resource) { return $resource('users', {}, { update: { method: 'PUT' }, deleteMember: { method: 'DELETE', url:'team/member/:userId/:teamId' }, addMember: { method: 'POST', url:'team/member' }, addTeam: { method: 'POST', url:'team' }, deleteTeam: { method: 'DELETE', url: 'team/:teamId' }, getTeam: { method: 'GET', url: 'team/:teamId' }, teams: { method: 'GET', url: 'team/list/:orgId' } }); } ]); 

you can reuse this service and implement it in any other service or controller, the better your controllers.

in case you want to change the user interface, since angular is declarative and not mandatory, it is not recommended to change the dom from the controllers, you will need to create directives, again directives can be reused across your entire system.

Stick to thin controllers, create services and directives, and you're good to go, and finally, I would recommend that you use yoman as a workflow and use cg-angular , it implements "best practices" for many things, including the folder structure of the application, which is very It is important to understand this from the very beginning.

+3
source

I think the best practice is to declare one controller for each form (view). You can also share functions and variables between controllers using services or $ rootScope

+1
source

I would use one controller and route for each view:

 /user/edit, userEditController.js, userEdit.html /user/view, userViewController.js, userView.html 
+1
source

Source: https://habr.com/ru/post/1207123/


All Articles