16

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() { ... });
2
  • 2
    Only declare it with the dependencies once, then just use angular.module('myApp'); Commented Dec 29, 2013 at 0:29
  • since app is the module, simpler to just do app.service('SessionService'.... And yes...it would be creating a new module as written, overwriting original Commented Dec 29, 2013 at 1:07

3 Answers 3

37

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.

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

2 Comments

Bingo. Declaring a module without dependencies reopens it for further definitions.
How do I add new dependencies from the callees?
7

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>

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.