AngularJS: Service in different file

All we need is an easy explanation of the problem, so here it is.

I’m learning AngularJS following an organization inspired by ng-boilerplate. I create different Angular modules for the different parts of my site.

However, I want to create all common elements (services and directives) under the main module, while having them all be in separate source files.

This code works, but is the module in sessionService.js referencing the same module than app.js, or is it creating a new one with the same name?

app.js

var app = angular.module('myApp', [...])
.config(...)
.controller(...);

sessionService.js

angular.module('myApp', [])
.service('SessionService', function() { ... });

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you call angular.module('myApp', []) multiple times on the same page, you will likely run into errors or conflicts. I never tried that.

However, if you already run angular.module('myApp', []) once. Then you can run angular.module('myApp') (note: without []) to retrieve (refer to) the myApp module you defined earlier.

Method 2

in controller.js file :

var app = angular.module('myApp',['newService']);

in service.js :

angular.module('newService',[])

.service('someService',function(){

    return {
         // return something
         return null
         }
    }

});

Do not forget to include both the js files in your HTML:

<script src="controllers/controller.js" type="text/javascript"></script>
<script src="services/service.js" type="text/javascript"></script>

Method 3

Naming & namespacing is important in any project. Try:

app.js:

var app = angular.module('myApp', ['sessionService', ...])...;

sessionService.js:

angular.module('sessionService', [])
.service('SessionService', ...);

Notice that the module name is in lower camel case while the service object itself is upper camel case. This will help you avoid namespace clashing. Hope that helps.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply