Different ways of bootstrapping AngularJS

AngularJS is neat and superheroic JavaScript MVW (Model View Whatever) Framework which allows to extend HTML capabilities with Directives, expression, two way binding. In this post, we will see different ways of bootstrapping AngularJS. Bootstrapping in AngularJS is nothing but just the initialization of Angular app.


There are two ways of bootstrapping AngularJS. One is Automatic Initialization and other is Manually using Script.

When you add ng-app directive to the root of your application, typically on the <html> tag or <body> tag if you want angular to auto-bootstrap your application.
<html ng-app="myApp">
When angularJS finds ng-app directive, it loads the module associated with it and then compile the DOM.

Another way to bootstrapping is manually initializing using script. Manual initialization provides you more control on how and when to initialize angular App. It is useful when you want to perform any other operation before Angular wakes up and compile the page. Below is the script which allows to manually bootstrap angularJS.
<script>
   angular.element(document).ready(function() {
      angular.bootstrap(document, ['myApp']);
   });
</script>
If you have noticed, it is using document.ready which is great as it will make sure that before bootstrapping your DOM is ready. You don't need to inclued jQuery library reference here, as angularJS has within it. So angular.bootstrap function bootstrap angularJS to document. The second parameter is the name of module. You need to take care of following things while using manual process.
  • Remember angular.bootstrap function will not create modules on the go. So you need to have your modules define, before you manually bootstrap. So below is the correct approach. First define the module and then bootstrap.
    <script>
        angular.module('myApp', [])
          .controller('MyController', ['$scope', function ($scope) {
            $scope.message= 'Hello World';
          }]);
    
       angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
       });
    </script>
    
  • You cannot add controllers, services, directives, etc after an application bootstraps.

And remember Don't mix up automatic and manual way of bootstrapping your app.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..