AngularJS: controller vs service

user776686 picture user776686 · Dec 10, 2014 · Viewed 26.1k times · Source

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?

Answer

Gil Moshayof picture Gil Moshayof · Dec 10, 2014

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.