Add AngularJS controller dynamically



Let me show you how to add angular controller dynamically: after application has bootstrapped. It is useful for example when you are loading components dynamically.


Inject angular module dynamically (add to dependencies)

A method .requires.push allows you to add dynamically another module as dependency to yours. So, that you will be able to use it’s services and directives.
The syntax is next:

angular.module('mainApp').requires.push('newApp');

Where the mainApp is your main module, and the newApp is one you’re adding dynamically.

So you get a mainApp with dependency of newApp:

angular.module('mainApp', ['newApp']);

Ok. With that method you can reach and use all services and directives of newApp, but not controllers.


Dynamically add module with controllers

To be able to use controllers of dynamically added module, you need to register controllers by $controllerProvider in your newApp you will be adding. Here is an example:

angular.module('newApp', [])
    .config(function($controllerProvider) {
        $controllerProvider.register('newAppCtrl', function() {
            // Your Code
        });
    });
angular.module('mainApp').requires.push('newApp');

Conclusion

To add new controller dynamically: