Index:

Now that we have modules it is time to try to understand what we can do with modules and why we need them in the end.

Let us start by saying that if we define something this something must be registered in a module, we’ll see soon what is the meaning of “define”. Going on with our comparison with the .net world, if we define a class this class must be defined in a namespace, or at least in an assembly.

At startup AngularJS iterates over all the referenced modules, declared and dependent, and performs its 2 phase startup:

  • Configuration Phase: each module has the option to execute a “config” phase, during this phase a module cannot rely on any other module since nothing is guaranteed to be configured or running at this time;
  • Run Phase: each module has the option to execute a “run” phase; at this time each module is guaranteed to be at least configured, so we can rely on other modules during this phase;

In order to hook in these phases we can write the following code:

<!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';
      
      var app = angular.module('my-app', []);
      app.config(function(){
        console.log('App config phase');
      });
      
      app.run(function(){
        console.log('App run phase');
      });
      
    }());
    </script>
</head>
<body data-ng-app="my-app">
    <input type="text" data-ng-model="name" placeholder="Write something here..." />
    {{name}}
</body>
</html>

Obviously we are not required to hook both phases.

We said that during the run phase, for example, we can rely on other modules. What does this means and how can we do that?

app.run(['$log', function($log){
        $log.debug('App run phase');
 }]);

We can replace a part of the above code with the sample just provided and see what happens looking at the browser console.
As you can imagine we are injecting dependencies into the run phase of the module: Dependency Injection will be our next topic.

Stay tuned.
.m