???? 在前面已經介紹了關于angularjs,以及擴展了一些jQuery ui的一些組件為angularjs的directive。在這里應進口007 在上篇留言我們來看看在angularjs中的DI特性。
??? DI:依賴注入,是一種軟件設計模式,應DIP依賴倒置原則,描述組件之間高層組件不應該依賴于底層組件。依賴倒置是指實現和接口倒置,采用自頂向下的方式關注所需的底層組件接口,而不是其實現。其應用框架則為IOC,在.net中有很多我們熟悉的IOC框架,如Unity,Castle windsor,Ninject,Autofact等等,其常常分為構造注入,函數注入,屬性注。同時在IOC和Service Locator(服務查找),如果你想更多的了解IOC和DI請參見martin fowler的Inversion of Control Containers and the Dependency Injection pattern。
???? 回到angularjs:在框架中為我們提供了angular.injector(modules)DI注入注射器。但是在我們使用注入的時候常常是不需要關心具體的如何注入。我們只需要按照其規則書寫我們的angularjs代碼就會很容易的得到angularjs的DI特性,DI方式有三種:
1:推斷式注入:在angularjs中我們可以在我們需要注入的地方按照名稱注入,這里要求參數名稱必須和注入服務實例名稱相同,一種名稱約定。angularjs會提取參數名稱查找相應DI實例注入。
例如:
?2?
?3?myModule.factory('$alert',?function($window)?{
?4?
?5?????return?{
?6?????????alert:?function(text)?{
?7?????????????$window.alert(text);
?8?????????}
?9?????};
10?});
11?
12?var?myController?=?function($scope,?$alert)?{
13?????$scope.message?=?function(msg)?{
14?????????console.log(msg);
15?????????$alert.alert(msg);
16?????};
17?};
18?myModule.controller("myController",?myController);?
?
在上面實例我利用已知的window服務新建了一個alert的服務.并利用注入到我們的controller使用.這里采用的都是約定注入(根據參數名稱注入).
jsfiddle在線演示http://jsfiddle.net/whitewolf/zyA5B/7/
?
2:標記注入:在angularjs中我們可以利用$inject標注DI注入,這里需要注入服務名稱的順序和構造參數名對應.這里可以解決以上約定的死板性.
將上例代碼改變為如下:
代碼如下:
?1?var?myModule?=?angular.module('myModule',?[]);
?2?
?3?myModule.factory('$alert',?['$window',?function($window)?{
?4?
?5?????return?{
?6?????????alert:?function(text)?{
?7?????????????$window.alert(text);
?8?????????}
?9?????};}]);
10?
11?var?myController?=?function($scope,?$alert)?{
12?????$scope.message?=?function(msg)?{
13?????????console.log(msg);
14?????????$alert.alert(msg);
15?????};
16?};
17?myController.$inject?=?['$scope',?'$alert'];
18?myModule.controller("myController",?myController);?
?
jsfiddle在線演示http://jsfiddle.net/whitewolf/zyA5B/8/
3:內聯注入:對于directives,factory,filter等特殊指令使用$inject標注注入使用不是那么友好,angularjs特別增加了內聯注入。如上面的$alert服務?????
2?
3????return?{?
4????????alert:?function(text)?{?
5????????$window.alert(text);?
6?????}?
7?};}]);
?
?? 在angularjs中我們可以在controller中實用DI特性,同時一些列的工廠方法如directives, services, filters同樣可以實用內聯注入得到DI特性。
1:在controller中形如:
?2?
?3?...
?4?
?5?}
?6?
?7?MyController.$inject?=?['dep1',?'dep2'];
?8?
?9??
10?
11?MyController.prototype.aMethod?=?function()?{
12?
13?...
14?
15?}
???
2:工廠方法注入形如:
?2?
?3?config(['depProvider',?function(depProvider){
?4?
?5?...
?6?
?7?}]).
?8?
?9?factory('serviceId',?['depService',?function(depService)?{
10?
11?...
12?
13?}]).
14?
15?directive('directiveName',?['depService',?function(depService)?{
16?
17?...
18?
19?}]).
20?
21?filter('filterName',?['depService',?function(depService)?{
22?
23?...
24?
25?}]).
26?
27?run(['depService',?function(depService)?{
28?
29?...
30?
31?}]);
?