articles

home / developersection / articles / creating custom modules in angularjs

Creating custom modules in Angularjs

Creating custom modules in Angularjs

Ashutosh Kumar Verma 3553 22-Apr-2025

Let us learn with a clear example what custom modules are in Angularjs, why they are used, and how to create them.

Modules in AngularJS

In Angularjs, a module is a container for different parts of an application, such as

  • Controllers
  • Directives
  • Filters
  • Services
  • Factories, etc.

Modules help organise your application into logical units and promote modularity, reusability, and testability.

Why create a custom module?

  • Separation of concerns: Put features or sections of an app in their own modules.
  • Reusability: Modules can be reused across different apps or features.
  • Maintainability: Smaller, isolated units are easier to manage and debug.
  • Dependency management: Easily inject and manage dependencies between modules.

 

How to create a custom module

Step 1: Define a Custom Module

// Defining a custom module named 'myCustomModule'
var myCustomModule = angular.module('myCustomModule', []);

Step 2: Add components to the custom module

Let's add a controller to this custom module,

myCustomModule.controller('MyController', function($scope) {
 $scope.message = "Hello from MyController in myCustomModule!";
});

 

Step 3: Use the custom module in the main application

// Main app module depends on 'myCustomModule'
var mainApp = angular.module('mainApp', ['myCustomModule']);

Step 4: Use in HTML

<!DOCTYPE html>
<html ng-app="mainApp">
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
 <script>
   // custom module
   var myCustomModule = angular.module('myCustomModule', []);
   myCustomModule.controller('MyController', function($scope) {
     $scope.message = "Hello from MyController in myCustomModule!";
   });
   // main module
   var mainApp = angular.module('mainApp', ['myCustomModule']);
 </script>
</head>
<body>
 <div ng-controller="MyController">
   <p>{{message}}</p>
 </div>
</body>
</html>

 

Also, read: What is an Angularjs module


Updated 22-Apr-2025

I'm a passionate content writer with a deep background in technology and web development. Skilled at writing engaging, well-researched, and SEO-friendly articles, I enjoy simplifying complex topics into clear and impactful writing that informs, inspires, and engages readers.

Leave Comment

Comments

Liked By