Search code examples
angularjsangularjs-service

When to use AngularJS service?


I'm teaching myself to program with AngularJS.

As a learning exercise, I'm attempting to rewrite an application I've written using jQuery to use Angular instead.

The program draws fractal images on a canvas element. The user inputs data into forms describing what fractal to draw, and then clicks a button. When the user clicks the button, the program draws the fractal.

It seemed rather straightforward to me to create an Angular controller to bind the data on the form.

Next, I asked myself how I can use Angular to do the actual drawing. In a book I'm reading, it says to use a service for "business logic" that "drives the application", rather than presentation logic.

That's fine and good, but... my existing code already provides an API for drawing the fractals. It seems to me that all I need do is bind the [Draw] button that the user clicks after filling the forms so that it calls my existing code. My book seems to suggest that I should create a "Drawing Service" and inject it into my controller; that the controller should then call a method on the service and pass in the configuration from the forms.

That sounds fine to me, but I'm asking myself... why do this? Why not simply have my Angular code call my drawing function the way it is now instead of putting it in a service?

I think that there is some aspect of Angular that I have failed to grasp, so I'm hoping to understand why I should use a service.

Just to be clear, I am not asking about the different between .service and .factory


Solution

  • You are never really required to use a service. However, in larger scale applications, separating logic between a controller and a service allows you to separate (decouple) the logic of the application.

    Services are most useful in cases where you re-use the same logic in multiple different areas of your application, or where the service implementation is complex enough to warrant independent testing or isolation. It is much easier to test a service with 10 lines of code than to try to test if those 10 lines of code worked inside a controller mixed with other functions.

    If you are working in a multiple developer environment, having a service will allow someone who is an expert on the UI work on the UI independently from someone who knows everything there is to know about how this specific function operates.

    Only you can determine when having a service is absolutely necessary, but most Agile developers will favor services whenever possible, and only use inline functions in a controller for trivial processes.