[英]Difference between two ways of injecting modules in Angular
在AngularJS中加載模塊的這兩種方式有什么區別:
var app = angular.module('app', ['ngRoute']);
// VERSION 1
app.controller('HomeCtrl', ['$scope', '$dep1', '$dep2', function($scope, $dep1, $dep2) {
// controller code
}];
// VERSION 2
function HomeCtrl($scope, $dep1, $dep2){
// controller code
}
HomeCtrl.$inject=['$scope', '$dep1', '$dep2'];
return HomeCtrl;
// Then load in the controller into the app module
app.controller('HomeCtrl', HomeCtrl);
兩種方式都用於縮小安全依賴注入。 這是源代碼的一個摘要, injector.js文件 :
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
// convert function to string, parse arguments
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
上面的代碼很好地解釋了如果你正在注入依賴項的函數,有類型的
Angular檢查此函數是否具有屬性$inject
,如果是,則此處是要注入的服務數組。
Angular從這個數組中獲取值,而不是最后一個元素,它應該是一個將值注入的實際函數。
注意我表示為注釋的部分// convert function to string, parse arguments
。 如果沒有配置$inject
屬性並提供控制器/服務/等。 實際上是一個函數類型,然后Angular將獲取函數的字符串表示並解析它接受的字面定義的參數。 然后獲得的參數數組將用作注入服務。
所以你可以看到差異很小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.