If you are reading up to this point, I assume you have the knowledge about AngularJS and/or RequireJS, and intend to integrate both, just like me, but there are not much practical information on the web. RequireJS is easy to use. Rather apply it directly to our existing project with fair complexity, I would take an approach to integrate it with a seed project from scrap, and I also take this chance to share how to get it done.
First of all, I use the popular Phonecat tutorial as an example to work with RequireJS. If you haven’t tried it before, please take a look at AngularJS.org. And you can get all the source code on my github for reference.
Modular design is good, but lack of dependency control is bad. Particularly when the Angular webapp become large and complex. It causes program break if the order of modules are not loaded in the order as expected. The followed diagram shows the dependency of the phonecat app. The phonecat module runs successfully only if all other modules are downloaded.
So you would prefer screen B to A as it load module more as the way you expect.
Okay, the idea is simple and we make the magic now. Let’s see the project structure shown in the followed image. The js folder is a typical template of AngularJS project with modules named animations, app, controllers, directives, filters, and services. Second, the main.js is the config file to define the dependency between the modules. In the lib folder, you need the RequireJS libaray. Third, I need to modify the index.html to add a bootstrap point to the RequireJS config.
The setup is already done. Now we can inject the dependency in your program (in a similar way you import the classes in Java) by wrapping up the code with a define function and a callback. The followed five screen shots show how easy it is, but be careful not to mix up the RequireJS module id and the Angular module id.
Here it is done. I hope you enjoy and it would be helpful.