AngularJS: angular.bootstrap with example

Hi Guys,

If you need to have more control over the initialization process, you can use a manual bootstrapping method instead i.e angular.bootstrap

If you have added ng-app and bootstrap method in same application, Angular will detect if it has been loaded more than once in browser. If it finds more than one script then it will load first script and will show warning message in browser console about subsequent script.
The usage of this is to prevent strange result in application otherwise multiple instance of Angular try to work on the DOM.

Eg.
<body ng-app="demoApp">
<div ng-controller="DemoController">
  {{welcomeMessage}}
</div>
</body>
  angular.bootstrap(document, ['demoApp']);









You can see bootstrap error. This error occurs while calling angular.bootstrap on an element that has already been bootstrapped. Here angular.bootstrap method already bootstrap app with "demoApp". And then angular find ng-app which throw error due to multiple instance of angular trying to access DOM.

This is the sequence that your code should follow:
1. After the page and all of the code is loaded, find the root element of your AngularJS application, which is typically the root of the document.
2. Call angular.bootstrap to compile the element into an executable, bi-directionally bound application.

Syntax

angular.bootstrap(element, [modules], [config]);

Arguments

element: DOM element which is the root of angular application.
modules: an array of modules to load into the application.
config: An object for defining configuration options for the application. The following keys are                        supported
             strictDi - disable automatic function annotation for the application. This is meant to assist in                finding bugs which break minified code. Defaults to false.

Example

index.html
<!doctype html>
<html>   
<head>  
<script src="angular.min.js"></script>  
<html>
<body>
<div ng-controller="DemoController">
  {{welcomeMessage}}
</div>

<script>
  var app = angular.module('demoApp', []);
  app.controller('DemoController', function($scope) {
      $scope.welcomeMessage = 'Hello world!';
  });
  angular.bootstrap(document, ['demoApp']);
</script>
</body>
</html>

Good Day :)

Post a Comment

0 Comments