简体   繁体   中英

best practice controller / services

I have built an Angular app that consumes data from different sources (SharePoint lists). I setup a controller for each source.

What is the best practice for this? Use only one controller for the app and different services? Or one service and one controller? Or multiple services and controllers? In the app I do not use routing.

I would say: use a controller for every "piece" of HTML in your app, (and it depends on the scale of your app how big that piece is, it could be just one controller if your app is really small). And use a service for each data source. Then you can use the services your need in your controllers. You could also use one service if you don't need a lot of behavior. It all depends on how big your application will be.

First I'd recommend reading these articles. Also, go through their angular implementation and see how they've achieved some of their effects. It will throw you in a world of problems that you'll feel like "Why? I mean, why? why did I ever got into this mess?" But, grit your teeth and get through it. Then you'll see how much you can achieve. Learning Angular JS is a never-ending cycle of this.

Ok, and to answer your question: your way isn't wrong.

But controllers are not designed to be used like that. Controllers are a unit of code which co-ordinates your data into the UI, handle UI events, etc. generally of a certain view - ie a portion of your UI (navigation bar, home page, edit form, etc.). Of course this can be your entire page as well. But it's best to break it down so that it's easier to manage.

Use services for what you described. Create a service for each data source or type of data (users, equipment, roles, etc.). I recommend that latter, since sometimes you need to pull data from multiple ends and tie them together. This can be done inside your controller as well, but having services will enable you to re-use that functionality in another part of your application.

To summarize a long answer, I'd say go through these articles, code and tips. Then build a structure that will help build your application. Just don't over-engineer it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM