UncleCoder.com

UncleCoder.com

Free programming examples and instructions

How to Bootstrap/Initialize an AngularJS App

How to Bootstrap/Initialize an AngularJS App

by Shabin Muhammed


Posted on 07 May 2018 Category: AngularJS Views: 61

Edited on 09 May 2018


An AngularJS app can be bootstraped in  two different ways

  1. Using the ngApp directive in HTML
  2. Using the angular.bootstrap('module-name') function

1. Using ngApp directive

<html ng-app="autoBootstrap">
  <body ng-controller="DemoController as ctrl">
    {{ctrl.data}}
  </body>
</html>

As you can see, the HTML tag has the angular directive ng-app. As soon as the angular.js script has loaded, AngularJS looks for the ng-app directive in HTML.
The HTML element which contains this directive now becomes you application's root. 

/*
 * Module declaration
 */
angular.module("autoBootstrap", []);  

/*
 * Controller Definition
 */
var DemoController = function($timeout){
	var ctrl = this;
    ctrl.data = "1...2...3...";
	$timeout(function(){
	    ctrl.data = "You go free....!!!";
	}, 2000)
}

/*
 * Adding controller to angular module with dependencies
 */
angular.module("autoBootstrap").controller("DemoController",["$timeout", DemoController]);

The Javascript is simple and contains only the module declaration and controller declaration and binding.
Live demo can be found here

2. Using angular.bootstrap()

<html>
  <body ng-controller="DemoController as ctrl">
    {{ctrl.data}}
  </body>
</html>

As you can see, the ngApp directive is missing from the HTML tag.

/*
 * Module declaration
 */
angular.module("manualBootstrap", []);

/*
 * Controller definition
 */
var DemoController = function($timeout){
    var ctrl = this;
    ctrl.data = "1...2...3...";
	$timeout(function(){
	    ctrl.data = "You go free....!!!";
	}, 2000);
};

/*
 * Controller binding
 */
angular.module("manualBootstrap").controller("DemoController",["$timeout", DemoController]);

/*
 * Wait for document ready event
 */
angular.element(document).ready(function() {
  /*
   * App bootstrap
   */
  angular.bootstrap(document, ['manualBootstrap']);
});

Also, the Javascript has an additional function inside a document.ready() function.

Live demo can be found here.


Which one should I use?

If your app requires some asynchronously fetched data, eg. some configuration information send by server, prior to bootstrap you can use the manual bootstrap method.
Otherwise, you are good with the automatic method.



Leave a Comment:


Advertisement