Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.


This post first appeared on JQuery By Example, please read the originial post: here

Share the post

Different ways of bootstrapping AngularJS

×

Subscribe to Jquery By Example

Get updates delivered right to your inbox!

Thank you for your subscription

×