Search code examples
javascriptangularjsangular-amd

Is it possible to lazy-load and inject angular modules into the app in runtime using angularAMD?


I have ng-grid as a dependency when defining the app:

var app = angular.module('myApp', ['ngGrid']);

But not all my views and controllers need ngGrid, so I was thinking if it could be possible to load and inject ngGrid into the app while defining the controllers which need it?

I tried somthing like this, but it didn't work:

app.js:

var app = angular.module('app',[]);

ProductListCtrl.js:

define(['app', 'ng-grid'], function (app) {
    'use strict';

    app.register.controller('ProductListCtrl', ['$scope', 'ngGrid', function ($scope) {
        name = $injector.get('ngGrid')
        $scope.name = name
    }]);

});

Any suggestions?


Solution

  • angularAMD provides an ngload RequireJS plugin allowing you to load existing AngularJS modules. Add ngload to your main.js then do:

    define(['app', 'ngload!ng-grid'], function (app) { ... }

    See documentation for more detail.