« Back to home

Bootstrapping an Angular JS app dynamically

Most of the code samples that you'll find regarding bootstrapping Angular JS is to do it declarative such as html ng-app=""

You can name your app or leave it blank if you only have 1 app (I find that in most cases, 1 app is enough although you can have multiple controller if needed).
What if you want to get away from the declarative approach and do all the App bootstrapping in JavaScript? I find that the code above works but is not flexible
especially on large-scale applications where you have a "layout" template and you know ahead of time that you're not going to use Angular JS on every single page.

If you want more flexibility when bootstrapping your Angular JS app, here's a code sample to accomplish that. Take note though that there's tons of other ways
to bootstrap an Angular JS app aside what I have here.

window.app = {};        

/** Bootstrap on document load and define the document along with optional 
modules as I have below.*/  
angular.element(document).ready(function () {  
    // Attach to namespace, bootstrap document, and inject modules.        
    app.ang = angular.bootstrap(document, ['ngResource', 'ngSanitize']);                   

    // OR simply, this works similarly.                    
    angular.bootstrap(document, []);        
});           

/** Define Angular Controller */        
app.myController= function ($scope, $resource, $timeout) {  
        ....    
};

Hope this helps some lost soul.

Comments

comments powered by Disqus