Search code examples
angularjsangularjs-service

Is it okay to have a function as an Angular service?


Usually AngularJS services are objects - no matter whether you create them using service, factory or provider.

Now I have a use case for a singleton function. Basically, I could solve this using a call to factory and by returning the function, such as:

angular.module('foo')
  .factory('bar', function () {
    return function () {
      // ...
    };
  });

This works, and whenever I ask for bar I get the inner-most function. Anyway, the fact that it works does not mean that it's a good idea.

So, is it? Or is it a bad one? If so, why?


Solution

  • Why not use value or constant? According to the docs they can take functions too.

    Register a constant service, such as a string, a number, an array, an object or a function, with the $injector.

    also from the docs of value:

    This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service.

    So I assume your approach is also valid.