To implement lazy loading of controllers in simple way, you have to do the following:
Save $controllerProvider.register
(which is the only method to add a controller into already bootstrapped AngularJS app) to variable in your app (main.js):
var app = angular.module('app',["ngRoute"]);
app.config(['$routeProvider', '$controllerProvider',
function($routeProvider, $controllerProvider) {
// remember mentioned function for later use
app.registerCtrl = $controllerProvider.register;
//your routes
$routeProvider.when("https://stackoverflow.com/", {templateUrl: 'partials/home.html'});
$routeProvider.when('/process1', {templateUrl: 'partials/process1.html'});
$routeProvider.otherwise({redirectTo: "https://stackoverflow.com/"});
}
]);
process1.html:
<script src="https://stackoverflow.com/questions/19434249/js/process1.js"></script>
<div ng-controller="P1Ctrl">
{{content}}
</div>
And now, in process1.js you use our registerCtrl
:
app.registerCtrl('P1Ctrl', function($scope)
{
$scope.content="...";
});
index.html probably remains the same. Check if your process1.js
is being loaded (simply using console.log()
right in the body of process1.js
, not in P1Ctrl
controller). If it isn’t, include jQuery before Angular:
<script src="https://stackoverflow.com/questions/19434249/lib/jquery/jquery.js"></script>
<script src="lib/angular/angular.js"></script>
IMPORTANT: This method doesn’t work with angular 1.2.0-rc.2 and 1.2.0-rc.3, because this little trick with jQuery doesn’t work.
For more complex (and prettier) solution, with .js
files as dependencies in route definitions, check that article: http://ify.io/lazy-loading-in-angularjs/ – it also works with rc.2 and rc.3. Here is plunk implementing described method: http://plnkr.co/edit/ukWikO5TVDtQ1l9WlrGD