Understanding Angular Dependency Injection
Dependency Injection in Angular can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider.
- factory
- value
- constant
- service
- provider
Full Stack Web Development Course Video
1. factory
It is a function which returns value. It produces value on demand when a service or controller needed.
2. value
It is a javascript object It passes values to controller config phase.
3. constant
Constants passes values at config phase considering the fact that value cannot be used to be passed during config phase.
4. service
It is a singleton javascript object which have a set of functions to execute certain tasks. It is defined by service() function.
5. provider
It is used to create factory, service etc. in config phase.
e.g.
<html>
<head>
<title> Dependency Injection in AngularJS</title>
</head>
<body>
<h1>Example of Dependency Injection</h1>
<div ng-app = "intellipaatApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "cube()">X<sup>3</sup></button>
<p>Result: {{result}}</p>
</div>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var intellipaatApp= angular.module("intellipaatApp", []);
//create a service using provider which describes a method cube to return cube of a number.
intellipaatApp.config(function($provide) {
$provide.provider('MultiplyService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b, c) {
return a * b * c;
}
return factory;
};
});
});
// make a value object as "defaultInput" and pass it a data
intellipaatApp.value("defaultInput", 2);
/*make a factory "MultiplyService" which gives a method multiply to return multiplication of three numbers */
intellipaatApp.factory('MultiplyService', function() {
var factory = {};
factory.multiply = function(a, b, c) {
return a * b * c;
}
return factory;
});
/* inject the factory "MultiplyService" in a service to use the multiply method of factory and make a service which defines a method cube to return cube of a number*/
intellipaatApp.service('CalcService', function(MultiplyService){
this.cube= function(a) {
return MultiplyService.multiply(a,a,a);
}
});
/* insert the value using its name "defaultInput" and
insert the service "CalcService" into the controller */
intellipaatApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.cube($scope.number);
$scope.cube= function() {
$scope.result = CalcService.cube($scope.number);
}
});
</script>
</body>
</html>
Output