π§ͺ AngularJS Dependency Injection & Injectable Services β Power Modular Development (2025 Guide)
π§² Introduction β Why Learn AngularJS Dependency Injection?
Dependency Injection (DI) is at the heart of AngularJS’s architecture. It allows components (like controllers, services, filters, and directives) to declare their dependencies, which are then automatically injected by AngularJS. This makes your application modular, testable, and reusable.
π― In this guide, youβll learn:
- What dependency injection is in AngularJS
- How to inject core and custom services
- Different ways to annotate dependencies
- Real-world usage of DI with examples and best practices
𧬠What is Dependency Injection in AngularJS?
Dependency Injection is a design pattern in which a component gets its dependencies from an external source rather than creating them manually.
Instead of doing this:
var http = new HttpService(); // tightly coupled
You do this:
app.controller('MyCtrl', function($http) { ... }); // injected
β AngularJS handles the object creation and lifecycle behind the scenes.
π§° AngularJS Built-in Injectables
| Injectable | Description |
|---|---|
$scope | Binds data between view and controller |
$http | Performs HTTP requests |
$location | Reads/modifies browser URL |
$timeout | Angular wrapper for setTimeout |
$interval | Angular wrapper for setInterval |
$routeParams | Access route parameters |
$q | Promise-based async logic |
β Basic Example of Dependency Injection
app.controller("MainCtrl", function($scope, $http) {
$http.get("/api/data").then(function(res) {
$scope.data = res.data;
});
});
π§Ύ $scope and $http are injected into the controller. AngularJS automatically resolves and provides these dependencies.
π§ͺ Creating a Custom Service and Injecting It
β Step 1: Define the Service
app.service("MathService", function() {
this.square = function(num) {
return num * num;
};
});
β Step 2: Inject into Controller
app.controller("CalcCtrl", function($scope, MathService) {
$scope.getSquare = function() {
$scope.result = MathService.square($scope.input);
};
});
β
AngularJS injects MathService into CalcCtrl automatically.
π Supported Injectable Types
| Type | Defined With | Usage Scope |
|---|---|---|
| Controller | app.controller | Connect logic to the view |
| Service | app.service | Singleton logic provider |
| Factory | app.factory | Return custom object/functions |
| Provider | app.provider | Configure service creation |
| Filter | app.filter | Format output in views |
| Directive | app.directive | Extend HTML functionality |
βοΈ Three Ways to Annotate Dependencies
1. Inline Annotation (Not Minification Safe)
app.controller("MyCtrl", function($scope, $http) { ... });
2. Array Annotation (Recommended for Production)
app.controller("MyCtrl", ["$scope", "$http", function($scope, $http) {
...
}]);
β This format survives minification because the dependency names are explicitly listed.
3. $inject Property Annotation
function MyCtrl($scope, $http) {
...
}
MyCtrl.$inject = ["$scope", "$http"];
app.controller("MyCtrl", MyCtrl);
β Useful when separating function definition from controller registration.
π§ Real-World Use Case β Injecting Custom API Service
app.factory("UserAPI", function($http) {
return {
getUsers: function() {
return $http.get("/api/users");
}
};
});
Injecting into controller:
app.controller("UserCtrl", function($scope, UserAPI) {
UserAPI.getUsers().then(function(res) {
$scope.users = res.data;
});
});
π Dependency Injection Hierarchy
- AngularJS creates a single instance of each service
- Controllers, directives, or filters share the same instance
- Reduces memory use and increases efficiency
π« Common Mistakes
| Mistake | Fix |
|---|---|
| Forgetting to list dependencies | Use array or $inject annotation |
| Typos in dependency names | Make sure service/param names are exact |
| Not using min-safe annotation | Always annotate for production environments |
π οΈ Best Practices
βοΈ Use array or $inject annotation in minified builds
βοΈ Inject servicesβnot logicβinto controllers
βοΈ Avoid tight coupling between services
βοΈ Create reusable services for API, math, date, etc.
βοΈ Keep service responsibilities focused (SRP principle)
π Summary β Recap & Next Steps
Dependency Injection in AngularJS is a core concept that simplifies code management, improves testing, and supports modular architecture. Whether you’re injecting built-in services or custom logic, understanding DI leads to cleaner, scalable applications.
π Key Takeaways:
- DI lets AngularJS provide objects like
$http,$scope, and custom services automatically - Use
app.service,app.factory, orapp.providerto create injectable components - Always annotate dependencies in production for minification safety
- Use services for reusable logic and controllers for view binding
βοΈ Real-world Relevance:
Used in apps where modular, testable, and maintainable architecture is criticalβlike dashboards, admin tools, finance systems, and API-driven platforms.
β FAQ β AngularJS Dependency Injection
β What is dependency injection in AngularJS?
β
It’s a design pattern where AngularJS automatically provides required components like $http, $scope, or custom services into your functions.
β What happens if I donβt annotate my dependencies properly?
β
AngularJS may fail to inject them correctlyβespecially after code minification in production builds.
β How are services different from factories in AngularJS?
β
Services use constructors and this, whereas factories return an object. Both are singleton and injectable.
β Can I inject a service into another service?
β
Yes. Services, factories, and providers can all inject each other in AngularJS.
Share Now :
