angularjs – Load all dependencies dynamically

Question:

In the index.php file I include all controllers:

<script src="app/app.js"></script>
<script src="app/ctrl_A.js"></script>
<script src="app/ctrl_B.js"></script>
<script src="app/ctrl_C.js"></script>
//etc...

This is not good, as I am loading javascript files that are not needed, for example, on the homepage.

In the app's .config I'm referring to the controller as follows:

app.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', 
function($urlRouterProvider, $stateProvider, $locationProvider) {
    $urlRouterProvider.otherwise("/login");
      $stateProvider
        .state('login', {
            url: "/login",
            templateUrl: "view/login.html",
            controller: 'ctrl_A'
        })
//...

How do I get dependencies (controller, factory, directive, ect…) to be loaded dynamically without declaring in index.php?

Answer:

I believe the best way is to use angularAMD . It basically pairs AngularJS with an asynchronous Javascript module loading definition called AMD, which does just what you expect.

Your index would just be a script like this:

<script data-main="app/app.js" src="app/libs/require.js"></script>

Transforming your code into AMD modules brings benefits to your project maintainability is not a difficult task.

Scroll to Top