Dependency Injection (Dependency injection, short di) is a software design pattern in which one or more dependencies (or services) are injected (or passed by reference) into a separate object (or client), It then becomes part of the client state.
This pattern separates the creation of client-dependent behavior, which makes programming loosely coupled and follows the principle of dependency reversal and single responsibility. In direct contrast to the service locator pattern, it allows the client to understand how the client uses the system to find dependencies-in a word, nothing you don't come to me, something I'll come to you.
AngularJS provides a good dependency injection mechanism. The following 5 core components are used as dependency injection:
- Value
- Factory
- Service
- Provider
- constant
value is a simple JavaScript object that is used to pass a value to the controller (configuration phase):
Define a module var Mainapp = angular.module ("Mainapp", []);//Create Value Object "Defaultinput" and pass Data Mainapp.value ("Defaultinput", 5); ...//inject "defaultinput" into the controller Mainapp.controller (' Calccontroller ', function ($scope, Calcservice, Defaultinput) { $ Scope.number = Defaultinput; $scope. Result = Calcservice.square ($scope. number); $scope. Square = function () { $scope. result = Calcservice.square ($scope. number); }});
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.
Define a module var Mainapp = angular.module ("Mainapp", []);//Create Factory "MathService" for two-number product provides a method multiply to RET Urn multiplication of numbersmainapp.factory (' MathService ', function () { var factory = {}; Factory.multiply = function (A, b) { return a * b } return factory;});//Inject factory "MathService" MA in Service Inapp.service (' Calcservice ', function (mathservice) { this.square = function (a) { return mathservice.multiply (a,a); }}); ...
Create a service, factory, etc. (configuration phase) through provider in AngularJS.
A factory method get () is provided in Provider, which is used to return value/service/factory.
Define a module var Mainapp = angular.module ("Mainapp", []);//Use provider to create a service definition a method for calculating the two-number product mainapp.config (function ( $provide) { $provide. Provider (' MathService ', function () {this . $get = function () { var factory = {}; Factory.multiply = function (A, b) { return a * b; } return factory;}) ;
constant (constant) is used to pass values during the configuration phase, noting that this constant is not available during the configuration phase.
Mainapp.constant ("Configparam", "constant value");
The following examples provide a demonstration of several dependency injection mechanisms.
AngularJS Dependency Injection