RequireJS with AngularJS application

1. Introduction

RequireJS is a javascript library that helps in loading all the dependent modules before loading a particular module. For example, when we say angular.module(‘app’, [‘a’,’b’,’c’]), this means that the app is the main/primary module that is dependent on modules a, b and c.

Another important point is that the objects of the loaded modules (a, b and c) are subsequently cached and are served when the same modules are required again.

While AngularJS provides Dependency Injection, RequireJS provides Dependency Management.

2. Integration of RequireJS with AngularJS

Let’s create a simple AngularJS application to understand a very basic integration with RequireJS.



3. Explanation

So we have defined three modules – the main app module (myApp), profession and todo. Within todo module, we have our controller defined. Note that the todo module is dependent on the profession module, basically because we wanted the profession field to be pre-populated before the other details could be filled out. So unless the profession module is loaded, the todo module will not load, and hence the application controller.

Same is the case when we are initializing our AngularJS application using angular.bootstrap. The initialization will happen only when the whole of the document and todo module has loaded successfully, while making sure all the scripts are included in the footer.

We should never use the ng-app directive when manually bootstrapping your app.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.