2015-08-20 19 views
3

我讀the Angular docs about injecting dependencies,和我試圖找出什麼「同步」的意思。

如在,保持事物'同步'和'保持事物'在同一順序'?文件似乎暗示它們之間有一些區別。

語境:

關於直列排列標記

當使用這種類型的註釋,注意保持註釋數組中的同步與函數聲明的參數。

關於$inject財產註釋

在這種情況下的$inject數組中的值的順序必須與myController的參數的順序相匹配。

就像數組註釋一樣,您需要注意保持$inject與函數聲明中的參數保持同步。

回答

2

在這種情況下,「同步」和「按順序」的含義相同。

的順序是在所有情況下重要除了Implicit Annotation(然而的隱式定義的函數將縮小/醜化過程中斷裂)

正如在這裏可以看到:

app = angular.module('myApp', []); 
// Inline Array Notation where we are defining the dependencies in the opposite order of what the function is defined as 
app.controller('myInlineCtrl', ['$http', '$scope', function ($scope, $http) { 
    $scope.testVal = '$scope passed as $scope'; 
    $http.testVal = '$http passed as $scope'; 
    // results in `$http passed as $scope` 
}]); 

// $inject Property Annotation 
var myInjectorCtrl = function ($scope, $http) { 
    $scope.testVal = '$scope passed as $scope'; 
    $http.testVal = '$http passed as $scope'; 
    // results in `$http passed as $scope` 
} 
// Inject the dependencies in the opposite order 
myInjectorCtrl.$inject = ['$http', '$scope']; 
app.controller('MyInjectorCtrl', myInjectorCtrl); 

以上測試表明我們必須注入順序而不是函數定義中參數的順序。這與能夠使用您希望的任何參數名稱(在合理範圍內)定義函數是一致的,例如當應用程序的minification出現時,函數本身可以被壓縮,但仍然使用正確的參數調用。

這方面的一個例子是這樣的:

// Define a controller with your own argument names 
app.controller('myMickeyMouseCtrl', ['$http', '$scope', '$timeout', function (mickey, donald, daffy) { 
    mickey.testVal = 'mickey passed as $scope'; 
    donald.testVal = 'donald passed as $scope'; 
    daffy.testVal = 'daffy passed as $scope'; 
    // results in `donald passed as $scope` 
}]); 

的所有三個http://jsfiddle.net/6qh2oyu6/

演示還需要注意的是,如果你定義myInjectorCtrl.$inject = ['$timeout'];隨後已經定義它,你將清除保存的注射是非常重要的控制器功能並且在這種情況下,它會導致僅與角$timeout功能被注入。

+0

對,所以訂單很重要。我明白了。 「同步」意味着什麼,而不是「按順序」? – Brendan

+1

我認爲你過分解讀成。我認爲在這種情況下,這兩個表達式的意思是相同的。 –

+0

太棒了。感謝你的回答! – Brendan