Manually Bootstrapping an Angular JS Application With Examples

Earlier we looked at various angular form features and its validation. In this post, We will discuss about angular initialization process and how to manually bootstrap an angular application if needed.

Automatically Bootstrapping an Angular Application

Let us have a look at the auto-bootstrap process in angular application that we have used so far. The following code shows the structure of the code, which we have written so far.

  • The script tag is placed at the bottom of the page to improve application load time. By placing script at the end, we can ensure that HTML loading is not blocked by angular.js script loading.
  • The ng-app directive can be placed anywhere in the application. That’s going to be the entry point of the application or angular will automatically bootstrap the application when it sees the ng-app directive.

Initialization Process

The following processes takes place in every angular application:

  1. Angular initializes automatically when DOM content is completely loaded or when the angular.js script is evaluated.
  2. Angular looks for the ng-app directive, if found then it loads the module associated with the ng-app directive.
  3. Then an application injector is created.
  4. This will retrieve object instances, instantiate types, invoke methods, and load modules.
  5. Compile the DOM elements treating the element containing ng-app directive as the root of the application.

Manually Bootstrapping an Angular Application

The automatic initialization will not work with asynchronously loaded data that need to perform an operation before Angular compiles a page. The angular will not wait until the loading of data if we rely on auto-initialization process. Therefore, in this scenario you need to have a better control over the initialization process.

Angular provides a method to control the bootstrap process programmatically or we say manually using angular.boostrap() method.

You should not use the ng-app directive if you use angular.bootstrap method.

Using angular.bootstrap() Example

The following example demonstrates how to use angular.bootstrap method to bootstrap an angular application.

We will first create a module and define a controller for our application.

app.js

The following script is used to bootstrap the application. We will pass our module name as the second parameter to the angular.bootstrap method. the first parameter is the document itself. When it is ready, we will bootstrap our application using this method.

bootstrapApp.js

Now we can include these two files in the HTML page and run our application.

index.html

You will see the following output on your browser.
bootstrap-450x71
That’s all about initialization process and we will see more features in the coming posts.

By admin

Leave a Reply

%d bloggers like this: