Developer Guide: Angular Services: Creating Angular Services

While angular offers several useful services, for any nontrivial application you'll find it useful to write your own custom services. To do this you begin by registering a service factory function that angular's DI will use to create the service object when it is needed.

The angular.service method accepts three parameters:

The this of the factory function is bound to the root scope of the angular application.

All angular services participate in dependency injection (DI) by registering themselves with angular's DI system (injector) under a name (id) as well as by declaring dependencies which need to be provided for the factory function of the registered service. The ability to swap dependencies for mocks/stubs/dummies in tests allows for services to be highly testable.

Following is an example of a very simple service. This service depends on the $window service (which is passed as a parameter to the factory function) and is just a function. The service simply stores all notifications; after the third one, the service displays all of the notifications by window alert.

    angular.service('notify', function(win) {
      var msgs = [];
      return function(msg) {
        msgs.push(msg);
        if (msgs.length == 3) {
          win.alert(msgs.join("\n"));
          msgs = [];
        }
      };
    }, {$inject: ['$window']});

Related Topics

Related API