AngularJS: app and modules
Index:
Last time we left with a really basic sample, so basic that in the real world it is pretty useless. In that sample there is too much magic, stuff works as expected but there is no evidence of why it works.
Modules
When AngularJS starts inspects at our markup looking for the data-ng-app attribute
<!DOCTYPE html> <html> <head> <title>My First Sample</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script> </head> <body data-ng-app> <input type="text" data-ng-model="name" placeholder="Write something here..." /> {{name}} </body> </html>
When the attribute is found AngularJS creates a module to “coordinate” our application. We can think at modules as assemblies in the .net world, or as namespaces. A module isolates stuff declared in it and a module can declare dependencies on other modules. Since in the above sample we are not defining a name for our application everything is done anonymously.
If we simply change the “data-ng-app” attribute to data-ng-app="my-app" our sample stops working immediately. It stops working because AngularJS now looks for a module called “my-app” that since is not defined anywhere breaks everything.
<!DOCTYPE html> <html> <head> <title>My First Sample</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script> <script type="text/javascript"> (function () { 'use strict'; angular.module('my-app', []); }()); </script> </head> <body data-ng-app="my-app"> <input type="text" data-ng-model="name" placeholder="Write something here..." /> {{name}} </body> </html>
Adding a single line of JavaScript resumes our sample: angular.module('my-app', []);
We are telling AngularJS to create a new module that has no dependencies (the empty array, the second parameter of the module method). So defining a module is as simple as calling the module method passing in the module name and a list of dependencies, if needed.
The question now should be: since it is just plain JavaScript why do we need to declare modules and dependencies?
- Order: giving an ordered shape and reduce the noise is important;
- Modules initialization, 2 phase startup, is the real reason behind modules definition;
2 phase startup will be the next topic.
.m