Why do I need angular.bootstrap even when I declare ng-app = "MyApp" in JSFiddle

I really don't understand why, at the end of my CoffeeScript code, I need to execute the angular.bootsrap document, ['MyApp'] , which controls the module and controllers in the following test application:

This is HTML:

 <div ng-app='InventoryModule' ng-controller='InventoryController'> <ul ng-repeat='item in items'> <li>{{item.title}}</li> <li>{{item.price | currency}}</li> </ul> </div> 

And CoffeeScript:

 inventoryModule = angular.module 'InventoryModule', [] inventoryModule.factory 'Items', -> items = {} items.query = () -> [{title: 'Hello', price: '5'}] items inventoryModule.controller 'InventoryController', ($scope, Items) -> $scope.items = Items.query() angular.bootstrap document, ["InventoryModule"] 

If you delete the last line, the application will not work. Why is this? This is not explained anywhere else.

This is the code script: http://jsfiddle.net/dralexmv/8km8x/11/

As you can see, the application really works. If you remove bootstrap , it will stop working.

+6
source share
2 answers

T; dg

Set the second drop-down list in jsFiddle for "No wrapper - in <head>" and you won't need the angular.bootstrap line.

Fiddle

Description

When the Angular library loads, it scans the DOM, looking for an element with the ng-app directive. When he finds one, he will begin the boot process.

In this process, Angular will take the value of the ng-app attribute ( InventoryModule in your case) and try to find the Angular module with the same name. If it fails, it will throw: Uncaught Error: No module: <module name> .

In your violin, you set the "Code Packing" field to the "onLoad" field. This drop-down list tells jsFiddle when to initialize the JS code that you put in the JS frame. When it is set to "onLoad", the code will run in the onLoad window event.

On the other hand, the Angular boot process will be executed on $(document).ready() , and since the $().ready event is fired before the onLoad event, Angular will try to initialize the InventoryModule module before the module is even defined, and what’s there, where the "No module" error will be "No module" .

angular.bootstrap() is a manual way to do the same thing that Angular already does a $().ready() handler in it .

+15
source

Take a look at the error console. Your code throws an exception:

 Uncaught Error: No module: InventoryModule 

I think this has something to do with it. As a rule, manual loading when calling angular.bootstrap bypasses the problem.

0
source

Source: https://habr.com/ru/post/948817/


All Articles