Load controller dynamically in AngularJS

If you are using routing in AngularJS then It’s very important to load controller dynamically. Otherwise, you have to load all controllers at the beginning which is not efficient.

We can load controller dynamically by resolve attribute of $routeProvider
.when function. Please have a look on sample code. Surely, You will understand that.

var app = angular.module ('hw',['ngRoute','ngResource']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider) {
app.registerCtrl = $controllerProvider.register;

function loadcontroller(controllerSubPath){
$.getScript("scripts/controllers/" + controllerSubPath + ".js").done(function( script, textStatus ) {
}).fail(function( jqxhr, settings, exception ) {
console.log( exception );

.when('/Rights',{templateUrl:'views/Right/search.html', controller:'SearchRightController', resolve: { load: function () {loadcontroller("right/searchRightController");}}})
redirectTo: '/'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s