38

How does AngularJS handle collisions between names of services? For example if I have declared two modules each containing a service called 'foo'. What would be a good way to "namespace" services if I want to create a reusable module or want to avoid collisions with other third-party modules?

2

2 Answers 2

40

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.

For the moment the best option is to prefix service names with a custom prefix, ex:

angular.module('myprefix_mymodule',['dep1', 'dep2']).factory('myprefix_MyService', ...)

Sign up to request clarification or add additional context in comments.

9 Comments

Personally I prefer to prefix it using dot symbol - it looks like real namespaces :) kind of factory('myModule1.myService')
@ValentynShybanov dots ate great but are pain in a neck for services if you don't minify your code. Normally it is not much of a problem if you control both your service and app but if you are writing a module for others it might be something to keep in mind. For simple experiments people might want to be forced to use DI annotations. But yeh, dots look better :-)
Only one note that you can't reference it directly via parameter name, only by array of names for DI: ['$scope', 'myModule1.myService', function($scope, myService) { ...}]
@pkozlowski.opensource if you're not creating your services with dependencies as Valentyn pointed out, you're doing it wrong. Dots should not be an issue - it's how we do it as well, and we have an application with over 100 services across 7 different, relatively large modules. We do the same for all our controllers, factories, providers, as well. The only two angular concepts you can't use it on - are directives and filters.
@Oddman thanks. The approach we're going down for filter and directive namespacing is with camelcasing. The angular docs suggest an underscore for namespacing filters, but underscore doesn't work for directive namespacing and had wanted something that would work for both for consistency.
|
8

As noted by pkozlowski, they don't. You can manually add a prefix to all of your services (which is kind of annoying), alternatively, I wrote a hack to namespace it for you. https://github.com/callmehiphop/angular-namespacer

1 Comment

I don't know that that's a hack, that's pretty slick, in fact, instead of namespace you might just modify module to do it automatically and even add a module method to what the main module method returns so that you can make sub-modules all nice and chained like! ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.