AngularJS 依賴注入

jopen 12年前發布 | 30K 次閱讀 JavaScript開發 angularjs

AngularJS為我們提供了angular.injector(modules) DI注入注射器。但是在我們使用注入的時候常常是不需要關心具體的如何注入。我們只需要按照其規則書寫我們的angularjs代碼就會很容易的得到angularjs的DI特性。

一般有三種方法來做依賴注入

推斷式注入

在angularjs中我們可以在我們需要注入的地方按照名稱注入,這里要求參數名稱必須和注入服務實例名稱相同,一種名稱約定。angularjs會提取參數名稱查找相應DI實例注入。

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);</pre>

標記注入

在angularjs中我們可以利用$inject標注DI注入,這里需要注入服務名稱的順序和構造參數名對應.這里可以解決以上約定的死板性。

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);</pre>

說明
在這里,

var myController = function($scope, $alert) {
    $scope.message = function(msg) {
        console.log(msg);
        $alert.alert(msg);
    };
};

我們可以將$scope$alert改為任意的參數名,但是myController.$inject = ['$scope', '$alert'];是必須要有的,且數組的元素與實際的服務名一致,順序與controller中的參數順序一致。

內聯注入

對于directives,factory,filter等特殊指令使用$inject標注注入使用不是那么友好,angularjs特別增加了內聯注入。如上面的$alert服務。

myModule.factory('$alert', ['$window', function($window) { 
   return { 
       alert: function(text) { 
       $window.alert(text); 
    };
}]);

這里的$window就是采用內聯注入的方式。
同樣的道理,在一些工廠方法中,比如controller、directive等,也可以采取這種方式來依賴注入。

angular.module('app', [])
.controller('controllerName', [
'dep1',
'dep2',
...,
function(dep1, dep2, ...) {
    ...
}]);

參考

  1. http://www.cnblogs.com/whitewolf/archive/2012/09/11/2680659.html
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!