Tuesday, 22 August 2017

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.
1<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.
1<script>
2   angular.element(document).ready(function() {
3      angular.bootstrap(document, ['myApp']);
4   });
5</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.
    01<script>
    02    angular.module('myApp', [])
    03      .controller('MyController', ['$scope'function ($scope) {
    04        $scope.message= 'Hello World';
    05      }]);
    06
    07   angular.element(document).ready(function() {
    08      angular.bootstrap(document, ['myApp']);
    09   });
    10</script>
  • You cannot add controllers, services, directives, etc after an application bootstraps.
  • https://www.codeproject.com/Articles/862602/Define-multiple-Angular-apps-in-one-page

No comments:

Post a Comment