Some of the components that have been introduced on Angularjs, as well as some of the jquery UI extensions, are ANGULARJS directive. Here should import 007 in the last message let's take a look at the di feature in Angularjs.
DI: Dependency Injection, a software design pattern, should dip dependency inversion to describe the high-level components between components should not rely on the underlying components. Dependency inversion refers to implementation and interface inversion, focusing on the underlying component interfaces that are required, rather than implementing them, in a top-down fashion. Its application framework is IOC, there are many familiar IOC frameworks in. NET, such as Unity,castle windsor,ninject,autofact, etc., which are often divided into structural injection, function injection, attribute note. At the same time in the IOC and service Locator (services lookup), if you want to learn more about IOC and DI see Martin Fowler's inversion control containers and the Dependency Injection pattern.
Back to Angularjs: a angular.injector (modules) Di injection syringe is provided in the framework. But when we use injections, we often don't need to be concerned with how we inject them. All we need to do is write our ANGULARJS code in accordance with its rules and it's easy to get Angularjs's di feature, Di has three kinds:
1: Inferred injection: In Angularjs we can inject by name where we need to inject the parameter name must be the same as the injection service instance name, a name convention. ANGULARJS extracts the parameter name to find the corresponding DI instance injection.
For example:
var mymodule = angular.module (' MyModule ', []);
Mymodule.factory (' $alert ', function ($window) {return
{
alert:function (text) {
$window. alert (text);
};
});
var mycontroller = function ($scope, $alert) {
$scope. message = function (msg) {
console.log (msg);
$alert. alert (msg);
}
;}; Mymodule.controller ("Mycontroller", Mycontroller);
In the example above I used the known window service to create a new alert service. and use the injected into our controller. Here is the convention injection (injected according to the parameter name).
Jsfiddle Online Demo http://jsfiddle.net/whitewolf/zyA5B/7/
2: Tag injection: In Angularjs we can use $inject to Mark di injection, where the order of the service names and the constructor parameter names are required. This can solve the rigidity of the above agreement.
Change the previous example code to the following:
The code is as follows:
var mymodule = angular.module (' MyModule ', []);
Mymodule.factory (' $alert ', [' $window ', function ($window) {return
{
alert:function (text) {
$ Window.alert (text);};
}]);
var mycontroller = function ($scope, $alert) {
$scope. message = function (msg) {
console.log (msg);
$alert. alert (msg);
}
;}; Mycontroller $inject = [' $scope ', ' $alert '];
Mymodule.controller ("Mycontroller", Mycontroller);
Jsfiddle Online Demo http://jsfiddle.net/whitewolf/zyA5B/8/