Add AngularJS controller dynamically
31 Jul 2016
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:
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
:
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:
Conclusion
To add new controller dynamically:
- Create new module and register new controller with
$controllerProvider
- Add your new module as a dependency dynamically with
.requires.push
method