Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an AngularJS module if it doesn't exist

I have several directives and factories spread over several files but I want all of them to be included inside the same module. For example:

user-account.js

var userModule = angular.module("user", []); //I create the module here
userModule.directive("userPicture", ...);

user-transactions.js

var userModule = angular.module("user"); //I use the module here
userModule.directive("userPayment", ...);

The problem I have is for this to work I need to include the files in the right order, otherwise it won't work since the creation of the module is only done in user-account.js. I don't like this since users for these modules would need to know the proper order for it to work.

So my question is, how can I structure my modules creation + usage in an elegant way? I was thinking on creating some kind of Singelton helper to create the module if it doesn't exist but I don't love the idea. Any other ideas?

like image 225
Emilio Rodriguez Avatar asked May 08 '26 11:05

Emilio Rodriguez


1 Answers

Don't mix the user module and the user-account in the same file.

app.js:

angular.module('myApp', ['user']);

user.js:

angular.module('user', []);

user-account.js:

angular.module("user").directive("userPicture", ...);

user-transactions.js:

angular.module("user").directive("userPayment", ...);

And then in your index.html:

<!-- modules -->
<script src="js/app.js"></script>
<script src="js/user.js"></script>

<!-- directives -->
<script src="js/directives/user-account.js"></script>
<script src="js/directives/user-transactions.js"></script>
like image 190
Davin Tryon Avatar answered May 09 '26 23:05

Davin Tryon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!