Reputation: 8655
I have read a couple of posts regarding proper usage of angularjs entities: services, factories, controllers and directives.
My particular concern is a comparison of a controller and a service. None of the posts though told me what is that a controller can do what service cannot and vice versa.
Can this be listed or is it just a matter of being canonical in angular's usage?
Upvotes: 40
Views: 31116
Reputation: 728
In addition to what have been said above. Controllers may also hold the logic of your application while the application isn't so big. But as you application grows you would need to move the logic to use services(like factory). This would allow variables and functions needed around your application to be easily accessible.
Upvotes: 2
Reputation: 10175
As per the AngularJS documentation, https://docs.angularjs.org/guide/concepts
Controllers are to do with view related business logic. Services, on the other hand, are to do with reusable business logic independent of the views.
Upvotes: 15
Reputation: 52837
controllers - responsibilities: initialize the view, mediate interaction between view/scope and services. It has dependencies on the view and model, but is more concerned with the view and making it work.
services - responsibilities: provides business services that is not dependent on the view or the controller. Its primary concern is delivering services, regardless of the consumer (controller/view/other services).
I'm not convinced if persistence factors into the differences.
Upvotes: 18
Reputation: 16761
Controllers are typically used to be bound with a view. Controllers manage a view's life cycle, and should be thought of as View Controllers. A new controller will be created for each instance of a view, meaning that if you navigate away from a certain view, and then back again - or if you have more than once instance of a certain view, a new controller will be created each time.
Services are typically used as the business logic of your application. Services are similar to singletons in the sense that they are created once, and the instance is maintained throughout the entire life cycle of your application. It is a good place to put your logical functions which many views or components will require, and also hold global cache which needs to be accessed throughout multiple areas in your application.
Upvotes: 80