Explanation of dependency Injection on Wki: Dependency injection is a software design pattern (DI) in which one or more dependencies (services) are injected (or passed by reference) into a separate object and then become part of that independent object.
Di separates the client from the creation of its own behavior, makes the programming pattern loosely coupled, and follows the dependency reversal and the single duty, the domain service locator pattern forms a direct contrast, and DI allows the client to understand how the client uses the system to find the dependency, as it can be understood: there's nothing you don't want to come to me for.
Angularjs provides a good dependency injection mechanism, and the following 5 core components are used as Dependency injection: value, factory, service, provider, constant. The following one by one easy to learn a bit.
1. Value
Value is a simple JavaScript object that is used to pass a value (configuration phase) to the controller, as in the following example:
var app=angular.modulr ("Demo", []);
App.value("Defaultinput", 5);
App.controller ("Mycontroller", Function ($scope, Calcservice,defaultinput) {
$scope. Number=defaultinput;
$scope. Result=calcservice.square ($scope. number);
$scope. Square=function () {
$scope. Result=calcservice.square ($scope. number);
}
});
2, Factory
Factory is a function used to return a value. Created when the service and controller are needed. Usually we use the factory function to calculate or return a value. Use examples as follows:
var app=angular.module ("MyApp", []);
App.factory ("MathService", function () {
var factory={};
Factory.multiply=function (A, b) {
return a*b;
}
return factory;
});
App.service ("Calcservice", function (MathService) {
This.suqare=function (a) {
Return mathservice.multiply (A,a);
}
});
3, Provider
In Angularjs, a service, factory, etc. are created through provider, and a factory method get is provided in provider for returning Value\service\factory.
var app=angular.module ("App", []);
App. Config (function ($provider) {
$provider. Provider ("MathService", function () {
this. $get =function () {
var factory={};
Factory.multiply=function (A, b) {
return a*b;
}
return factory;
}
});
});
4, constant
Constant is used to pass values during the configuration phase, but be aware that this constant is not available during the configuration phase.
App.constant ("Configprogram", "constant value");
Angularjs Dependency Injection