🧩 AngularJS Modules & Architecture
Estimated reading: 4 minutes 26 views

🧰 AngularJS NgModules & Configuration Patterns (2025 Guide)

🧲 Introduction – Why Understand NgModules and Configuration Patterns?

In AngularJS, NgModules (or simply β€œmodules”) form the foundational building blocks for organizing applications. They help in grouping components, services, filters, directives, and routing logic into cohesive blocks of functionality. While AngularJS doesn’t use the @NgModule decorator like Angular 2+, its module system supports structured configuration through .config(), .run(), and dependency declarations.

Mastering module configuration patterns allows developers to create scalable, maintainable, and testable AngularJS applicationsβ€”especially in enterprise-grade or legacy systems.

🎯 In this guide, you’ll learn:

  • What NgModules are in AngularJS
  • How to declare and configure modules properly
  • The purpose of .config() and .run() blocks
  • Real-world examples of modular configurations

🧩 What Is an NgModule in AngularJS?

In AngularJS, a module is a container for the various parts of your application: controllers, services, filters, directives, etc. It also defines application dependencies and can be configured at runtime.

var app = angular.module('myApp', []);

🧾 Explanation:

  • 'myApp': Name of the module.
  • []: Dependency list (empty for now).

Modules encourage a modular architecture where features and utilities can be split across different files and loaded as needed.


πŸ“¦ Declaring Multiple NgModules

You can create multiple modules for separation of concerns:

angular.module('userModule', []);
angular.module('productModule', []);
angular.module('sharedModule', []);

And inject them into the root module:

angular.module('myApp', ['userModule', 'productModule', 'sharedModule']);

βš™οΈ Using .config() for Application Setup

The .config() method is used to configure providers before the app runs. This is the right place for setting up:

  • Routes
  • Custom service providers
  • Constants
  • Interceptors
app.config(function($locationProvider, $httpProvider) {
  $locationProvider.html5Mode(true);
  $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
});

🧾 Explanation:

  • $locationProvider enables HTML5 routing.
  • $httpProvider customizes default HTTP headers.

πŸ§ͺ Common .config() Use Case – Routing Setup

app.config(function($routeProvider) {
  $routeProvider
    .when('/home', {
      templateUrl: 'home.html',
      controller: 'HomeCtrl'
    })
    .otherwise({ redirectTo: '/home' });
});

🧾 Purpose: Defines view-controller mappings for SPA navigation.


πŸš€ Using .run() for Application Initialization

The .run() block executes after the injector is created, useful for app-wide behavior.

app.run(function($rootScope) {
  $rootScope.appTitle = "My AngularJS App";
});

🧾 Use Cases:

  • Setting global variables
  • Watching authentication status
  • Logging/analytics initialization

πŸ“˜ Full Example – Modular Configuration

🧱 Step 1: Shared Module

angular.module('sharedModule', [])
  .constant('APP_VERSION', '1.0.0');

πŸ“¦ Step 2: User Module

angular.module('userModule', [])
  .controller('UserCtrl', function($scope) {
    $scope.name = "John Doe";
  });

πŸš€ Step 3: Root Module

angular.module('myApp', ['sharedModule', 'userModule'])
  .config(function($logProvider) {
    $logProvider.debugEnabled(true);
  })
  .run(function($rootScope, APP_VERSION) {
    $rootScope.version = APP_VERSION;
  });

πŸ“ Suggested Folder Structure for Modular AngularJS Apps

angularjs-app/
β”‚
β”œβ”€β”€ index.html
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ app.module.js         β†’ Root module
β”‚   β”œβ”€β”€ app.config.js         β†’ .config() block
β”‚   β”œβ”€β”€ app.run.js            β†’ .run() block
β”‚
β”œβ”€β”€ user/
β”‚   β”œβ”€β”€ user.module.js
β”‚   β”œβ”€β”€ user.controller.js
β”‚
β”œβ”€β”€ shared/
β”‚   └── shared.module.js
β”‚   └── constants.js

βœ… Benefits of Modular Configuration Patterns

βœ”οΈ Better code organization – Easier to manage large codebases
βœ”οΈ Lazy loading ready – Each feature can load independently
βœ”οΈ Testability – Isolated modules and components are easier to test
βœ”οΈ Scalability – Add or remove features without breaking the root app
βœ”οΈ Maintainability – Clean separation of concerns


πŸ“Œ Summary – Recap & Next Steps

AngularJS NgModules and configuration patterns allow you to build structured, testable, and scalable applications. By breaking your app into modules and leveraging .config() and .run() blocks, you gain fine control over initialization, routing, dependency setup, and runtime behavior.

πŸ” Key Takeaways:

  • Declare modules using angular.module()
  • Use .config() for routing and provider setup
  • Use .run() for initialization logic
  • Inject sub-modules into the root app to organize features

βš™οΈ Real-world Relevance:
Large AngularJS applicationsβ€”especially dashboards, CMSs, and enterprise appsβ€”depend heavily on clean module configuration for long-term sustainability.


❓ FAQ – AngularJS NgModules & Configurations


❓ What is the difference between .config() and .run() in AngularJS?
βœ… .config() is used to configure providers before the app runs, while .run() executes logic after the app is initialized.


❓ Can I have multiple modules in one app?
βœ… Yes. It’s a best practice to split your app into feature, shared, and routing modules for better structure.


❓ Should I define constants in config or run?
βœ… Use .constant() in a shared module, and access it in both .config() and .run() blocks.


❓ What happens if I inject a module twice?
βœ… AngularJS ignores duplicate module injections to prevent duplication or error.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🧰 AngularJS NgModules & Configuration Patterns

Or Copy Link

CONTENTS
Scroll to Top