Reputation: 1387
I think the answer to this question is "no" but I'm asking it anyways as I cant seem to find a definitive answer.
Can angularjs load controllers on the fly?
To explain further, I have an angular app that is bootstrapped the default way, via ng-app.Example, the index.html file:
<!doctype html>
<html>
<head>
<title>myapp</title>
</head>
<body ng-app="app">
...
<app-body></app-body>
<script src="lib/angular/angular.min.js"></script>
<script src="app/app.js"></script>
...
Inside the app module, I have a route setup, something like this:
$routeProvider
.when('/Home', {
templateUrl: 'home/home.html',
controller: 'HomeController'
})
.when('/Behaviors', {
templateUrl: 'contact/contact.html',
controller: 'ContactController'
});
// etc.
I was curious - is there a way to load the HomeController.js file when the user goes to that route? So that js file is not set in the index.html above, but inside the home/home.html:
<script src="home/HomeController.js"></script>
Is something like this possible?
Upvotes: 1
Views: 389
Reputation: 36
Yes, AngularJS is able to dynamically load route controllers and dependencies such as factories. It would require the use of RequireJS. RequireJS would be your entry point, which would load Angular.
The angular route's resolve property would kick off a call to some code that resolved a file via RequireJS. Since the resolve property utilizes promises the route won't load until the file is loaded.
Alternatively you could optimize an app using something like GulpJS, Gulp-angular-template cache, concat, uglify, etc. Here is an example:
Upvotes: 2