I am from asp.net mvc background and have recently started with Angularjs. I have a simple entity named Account
that is exposed through RESTful asp.net web api. I am now creating its client side with Angular. On client side I have views like create, edit, list and detail.
Should I be creating a controller for each view or should there be only one controller named `accountsController' for all CRUD operations? What is the standard practice in this scenario?
Don't look to controllers in terms of "operations" like CRUD, in this case yu are "talking to a restful API", since restful services uses the HTTP verbs to map CRUD operations, like:
PUT, POST -> Create
GET -> Read
POST -> Update
DELETE -> Delete
A good practice is to create angular services and return a $resource for later usage, map the $resource to your CRUD endpoints like this:
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 that service and inject it in any other service or controller, the slimmer your controllers the better.
in the case you would like to modify the UI since angular is declarative and not imperative isn't recommended to modify the dom from controllers, you'll need to create directives again directives can be reused through your whole system.
Stick to slim controllers, create services and directives and you are good to go and finally I'd recommend you to use yeoman as a workflow and use cg-angular generator, it implements the "best practices" for many things including application folder structure which is very important to get it right since the beginning.
I think the best practice is to declare one controller for each form(view). Also you can share functions and variables between controllers using services or $rootScope
i would use one controller and route per each view:
/user/edit, userEditController.js, userEdit.html
/user/view, userViewController.js, userView.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With