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
Leave Comment