天天看點

再談angularjs DI(Dependency Injection)

     回到angularjs:在架構中為我們提供了angular.injector(modules)di注入注射器。但是在我們使用注入的時候常常是不需要關心具體的如何注入。我們隻需要按照其規則書寫我們的angularjs代碼就會很容易的得到angularjs的di特性,di方式有三種:

1:推斷式注入:在angularjs中我們可以在我們需要注入的地方按照名稱注入,這裡要求參數名稱必須和注入服務執行個體名稱相同,一種名稱約定。angularjs會提取參數名稱查找相應di執行個體注入。

例如:

再談angularjs DI(Dependency Injection)

 1 var mymodule = angular.module('mymodule', []);

 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);​

再談angularjs DI(Dependency Injection)

在上面執行個體我利用已知的window服務建立了一個alert的服務.并利用注入到我們的controller使用.這裡采用的都是約定注入(根據參數名稱注入).

2:标記注入:在angularjs中我們可以利用<code>$inject标注di注入,這裡需要注入服務名稱的順序和構造參數名對應.這裡可以解決以上約定的死闆性.</code>

<code>将上例代碼改變為如下:</code>

<code>代碼如下:</code>

<code></code>

再談angularjs DI(Dependency Injection)

<code></code><code> 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);​</code>

再談angularjs DI(Dependency Injection)

<code> </code>

3:内聯注入:對于directives,factory,filter等特殊指令使用$inject标注注入使用不是那麼友好,angularjs特别增加了内聯注入。如上面的$alert服務     

再談angularjs DI(Dependency Injection)

1 mymodule.factory('$alert', ['$window', function($window) { 

3    return { 

4        alert: function(text) { 

5        $window.alert(text); 

6     } 

7 };}]);

再談angularjs DI(Dependency Injection)

   在angularjs中我們可以在controller中實用di特性,同時一些列的工廠方法如directives, services, filters同樣可以實用内聯注入得到di特性。

1:在controller中形如:

再談angularjs DI(Dependency Injection)

 1 var mycontroller = function(dep1, dep2) {

 3 ...

 5 }

 6 

 7 mycontroller.$inject = ['dep1', 'dep2'];

 8 

 9  

10 

11 mycontroller.prototype.amethod = function() {

12 

13 ...

14 

15 }

再談angularjs DI(Dependency Injection)

2:工廠方法注入形如:

再談angularjs DI(Dependency Injection)

 1 angualar.module('mymodule', []).

 3 config(['depprovider', function(depprovider){

 5 ...

 7 }]).

 9 factory('serviceid', ['depservice', function(depservice) {

11 ...

13 }]).

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 }]);

再談angularjs DI(Dependency Injection)

繼續閱讀