Mastering Web Application

(Rick Simeone) #1

Angular Zen


The run phase


The run phase allows us to register any work that should be executed upon the
application's bootstrap. One could think of the run phase as an equivalent of the
main method in other programming languages. The biggest difference is that
AngularJS modules can have multiple configure and run blocks. In this sense,
there is not even a single entry point (a running application is truly a collection
of collaborating objects).


To illustrate how the run phase could be useful, let's imagine that we need to display
application's start time (or uptime) to the users. To support this requirement, we
could set application's start time as a property of the $rootScope instance as follows:


angular.module('upTimeApp', []).run(function($rootScope) {
$rootScope.appStarted = new Date();
});

And then retrieve it any template, as given in the following code:


Application started at: {{appStarted}}

In the example showing the run block in action we are setting
properties directly on the $rootScope instance. It is important
to realize that the $rootScope instance is a global variable and it
suffers from all the problems of a global state. The $rootScope
instance should be used to define new properties only sparingly and
only for properties that need to be accessible in many templates.

Different phases and different registration methods


Let's summarize different methods of creating objects and how those methods
correspond to module's lifecycle phases:


What gets registered? Injectable during the
configuration phase?

Injectable during
the run phase?
Constant Constant's value Yes Yes
Variable Variable's value - Yes
Service A new object created by a
constructor function


  • Yes


Factory A new object returned from
a factory function


  • Yes


Provider A new object created by the
$get factory function

Yes -
Free download pdf