AngularJS app.run() documentation?
Categories:
Understanding and Utilizing AngularJS app.run()

Explore the app.run()
method in AngularJS, its purpose, execution order, and best practices for application-wide initialization tasks.
The app.run()
method in AngularJS is a crucial component for executing code once your application has been loaded and configured. It's often misunderstood or underutilized, but mastering its use can significantly improve your application's startup logic and overall architecture. This article delves into what app.run()
is, when and how to use it effectively, and provides practical examples to illustrate its power.
What is app.run() and When Does It Execute?
The app.run()
method is part of the AngularJS module API. It allows you to register a block of code that will be executed after all services have been loaded and instantiated, and after the injector has been created. This makes it an ideal place for application-wide initialization tasks that depend on services or require interaction with the root scope.
Unlike configuration blocks (.config()
), which run during the module loading phase and can only inject providers, app.run()
blocks run during the execution phase. This means they can inject instances of services, factories, and values, making them much more flexible for operational logic.
flowchart TD A[Module Loading] --> B{app.config() Blocks} B --> C[Service Provider Registration] C --> D[Injector Creation] D --> E{app.run() Blocks} E --> F[Application Bootstrap] F --> G[Application Ready] subgraph AngularJS Lifecycle A B C D E F G end
AngularJS Application Lifecycle with app.run() Execution
Common Use Cases for app.run()
The flexibility of app.run()
makes it suitable for a variety of application-level tasks. Here are some common scenarios where it shines:
- Authentication and Authorization: Checking user authentication status, redirecting unauthenticated users, or setting up global authorization checks.
- Global Event Listeners: Attaching event listeners to the
$rootScope
for handling application-wide events, such as route changes ($routeChangeStart
,$routeChangeSuccess
). - Initial Data Loading: Fetching essential application data (e.g., user profiles, configuration settings) that is required before any view is rendered.
- Third-Party Library Initialization: Integrating and initializing third-party libraries that require AngularJS services or the application's root scope.
- Setting up Global State: Initializing global variables or services that need to be available throughout the application.
angular.module('myApp', ['ngRoute'])
.run(function($rootScope, $location, AuthService) {
// Listen for route changes
$rootScope.$on('$routeChangeStart', function(event, next, current) {
// Check if the route requires authentication
if (next.authenticate && !AuthService.isAuthenticated()) {
$location.path('/login');
}
});
// Perform initial data load
AuthService.loadCurrentUser().then(function(user) {
$rootScope.currentUser = user;
});
console.log('Application run block executed!');
});
Example of app.run() for authentication and initial data loading
app.run()
is powerful, avoid putting too much complex logic directly into it. If your initialization logic becomes extensive, consider encapsulating it within a dedicated service and then injecting and calling that service from your app.run()
block. This promotes better separation of concerns and testability.Injecting Dependencies into app.run()
Just like controllers, services, and factories, app.run()
blocks can inject dependencies. You can inject any service, factory, value, or constant that has been defined in your AngularJS application. This is a key difference from app.config()
, which can only inject providers.
The dependencies are passed as arguments to the function registered with app.run()
. AngularJS's dependency injector handles the instantiation and provision of these services.
angular.module('myApp')
.value('appName', 'My Awesome App')
.factory('LoggerService', function() {
return {
log: function(message) {
console.log('[Logger]', message);
}
};
})
.run(function($rootScope, appName, LoggerService) {
$rootScope.appName = appName;
LoggerService.log('Application started with name: ' + appName);
});
Injecting a value and a factory into app.run()
app.run()
. While possible, if your application's core functionality depends on the completion of these operations, you might need to manually bootstrap AngularJS after the async task is done, or use a promise-based approach to delay certain actions until the data is ready. However, for most cases, app.run()
is suitable for initiating async tasks that don't block the initial rendering.