How to use two AngularJS services with same name from different modules?

Golo Roden picture Golo Roden · Jul 25, 2013 · Viewed 12.9k times · Source

Supposed I have two modules for AngularJS, e.g. foo and bar, and both of them define a service called baz.

In my application I depend on them by saying:

var app = angular.module('app', [ 'foo', 'bar' ]);

Then I can try to use the baz service in a controller by using

app.controller('blaController', [ '$scope', 'baz', function($scope, baz) {
  // ...
}]);

How can I define which of the two services I'd like to use? Is there something such as a fully-qualified name?

Answer

Eduard Gamonal picture Eduard Gamonal · Jul 25, 2013

The service locator looks services up by name (angularjs guide DI). However "Namespacing" services in AngularJS:

As of today AngularJS doesn't handle namespace collisions for services so if you've got 2 different modules with the service named the same way and you include both modules in your app, only one service will be available.

I guess you can make the fully qualified name "by hand": name the service foo.baz and bar.baz instead of plain baz. It's kind of a self-delusion. Moreover, writing it this way doesn't make namespacing real, but another person that reads the code might think so.