Angularjs – controller, services & promises

As promised this time I will write something about the usage of controllers together with services and of course also promises.

Sources are available here: angular-example – 01

Generally spoken it’s quite easy. The only thing that has to be kept in mind that all service calls are asynchronous. So imho the best way is to have very simple services that return the result and let the controller handle both events (see P1Controller).

Service method:


Additionally I would like to introduce to utilities I really like: the semaphore and the status object (both are found in utility module).

I use the semaphore to check if there is already a service call running at the moment:

Normally also a controller has a status. Mostly this is some undefined status, success and error. Therefore I built an object called status.

This makes it really easy in the frontend partial to control and display stuff like error or success messages:

I experienced very often that there is a need of e.g. doing filtering of the data so that a controller doesn’t need all the data that a service is returning or some calculation or enrichment of the data has to be done. Then in my experience it is very good to do the transformation in the service and return a promise/future to the controller (as in P2Controller).

Service method:


So, I hope that clarifies some things.

Next time I will turn to directives and how to use them for form field validation. But this will take some time because I’m on holiday. Anyway have a nice weekend!

GD Star Rating
Angularjs - controller, services & promises, 8.5 out of 10 based on 2 ratings

Ein Gedanke zu „Angularjs – controller, services & promises“

  1. Nice explanation!

    Why not keeping the request-state in the service, which is by default a singleton?

    Therefore no semaphore-structure is needed. Perhaps one can extend the promise-prototype to add another callback for „running“, to inform the callee about an ongoing concurrent request.

Kommentar verfassen

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.