When to use service over controller in AngularJS application?
AngularJS is a great framework that has many parts that developers need to understand to write a well crafted web application. In this post, I’ll tell you the reasons & use case that will guide you when to use service over controller in angularjs application.
I’ve seen many examples online where controllers are really thick and performs the job that is easily achievable by using services. A small size application may not need this but it’s good to know the concepts and implement them in correct way irrespective of the size of an application. Let us see, how both of the concepts actually work in the framework.
A controller is instantiated every-time a linked state/url is requested. The object that is received by this instantiation may have properties, methods and the state. You can use inheritance to reuse the properties, methods, state of a controller in a derived controller. So, in this way, a controllers hierarchy can be created based on inheritance and all of the scope of other controllers will be available to the last controller in hierarchy.
The above inheritance concept solves a problem when the state to share is logically related and thus, there is a reason to define related controllers that derives from another. But this state, properties or methods will not be available to other controllers as a controller by nature is instantiated every time as well as a controller not in inheritance hierarchy will not be able to use other controller’s members or state that are in the inheritance hierarchy.
A service can be used as a central place to make any HTTP calls to the server. It can act as a layer that maps to the entities that server and client understands. For example, a service can get a response from one or more server calls and give back an entity that controller can easily understand. This makes such mapping done at a central location when the application is big. This may also differ if your app uses $resource service available in the framework as this service uses REST convention to form up an entity on the client and the members of this will mostly resemble what is defined on the server. But a mapping can be needed anytime and one should not scatter mapping layer as that is not maintainable.
Separating the above discussed concerns also helps in writing tests for controllers, services. Above is my reasonings, theoretical knowledge about controllers & services. Read my other AngularJS posts to learn more.