javascript - angularjs怎么知道回調函數里需要什么參數?
問題描述
例如這樣
app.controller(’myCtrl’, function($scope, $rootScope) { // 將$rootScope改成其他名字就不行了。 $scope.names = ['Emil', 'Tobias', 'Linus']; $rootScope.lastname = 'Refsnes';});
angular是怎么知道我第二個參數需要$rootScope?
問題解答
回答1:因為 AngularJS 提供兩種注入方式。一種叫 implicit dependency injection(隱式依賴注入),一種叫 explicit dependency injection(顯式依賴注入)。
你的代碼中,使用的是第一種,隱式依賴注入:
app.controller(’myCtrl’, function($scope, $rootScope) { $scope.names = ['Emil', 'Tobias', 'Linus']; $rootScope.lastname = 'Refsnes';});
由于 $scope 和 $rootScope 都是 AngularJS 的 built-in service,因此 AngularJS 可以找到你想要注入的東西。但如果你改成 rootScope,這樣 AngularJS 就從自己的框架中找不到了。
如果使用顯式依賴注入,就是這樣:
app.controller(’myCtrl’, [’$scope’, ’$rootScope’, function(whatever, blah) { whatever.names = ['Emil', 'Tobias', 'Linus']; blah.lastname = 'Refsnes';}]);
這樣 AngularJS 就會根據顯式聲明的 $scope 和 $rootScope 去找。那么你在匿名函數的參數里,設置成什么都沒關系。注意先后順序就好。
或者,你也可以通過手動調用 $inject 來實現。就像這樣:
var myController = function($scope, $rootScope) { $scope.names = ['Emil', 'Tobias', 'Linus']; $rootScope.lastname = 'Refsnes';});myConroller.$inject = [’$scope’, ’$rootScope’];app.controller(’myCtrl’, myController);
詳情請參考文檔:https://docs.angularjs.org/gu...Dependency Annotation 那一部分。
文檔中同樣提醒了你,如果你打算壓縮代碼,那就不要使用隱式依賴注入。
相關文章:
