javascript - angularjs怎么知道回調(diào)函數(shù)里需要什么參數(shù)?
問題描述
例如這樣
app.controller(’myCtrl’, function($scope, $rootScope) { // 將$rootScope改成其他名字就不行了。 $scope.names = ['Emil', 'Tobias', 'Linus']; $rootScope.lastname = 'Refsnes';});
angular是怎么知道我第二個(gè)參數(shù)需要$rootScope?
問題解答
回答1:因?yàn)?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 就會(huì)根據(jù)顯式聲明的 $scope 和 $rootScope 去找。那么你在匿名函數(shù)的參數(shù)里,設(shè)置成什么都沒關(guān)系。注意先后順序就好。
或者,你也可以通過手動(dòng)調(diào)用 $inject 來實(shí)現(xiàn)。就像這樣:
var myController = function($scope, $rootScope) { $scope.names = ['Emil', 'Tobias', 'Linus']; $rootScope.lastname = 'Refsnes';});myConroller.$inject = [’$scope’, ’$rootScope’];app.controller(’myCtrl’, myController);
詳情請(qǐng)參考文檔:https://docs.angularjs.org/gu...Dependency Annotation 那一部分。
文檔中同樣提醒了你,如果你打算壓縮代碼,那就不要使用隱式依賴注入。
相關(guān)文章:
1. JSP頁面導(dǎo)入問題類文件放在WEB-INF / classes中的包中2. html5和Flash對(duì)抗是什么情況?3. ddos - apache日志很多其它網(wǎng)址,什么情況?4. mysql - redis和mongodb怎么結(jié)合5. 導(dǎo)入數(shù)據(jù)庫不成功6. PHP類中的$this7. mysql如何配置遠(yuǎn)程php外網(wǎng)鏈接數(shù)據(jù)庫8. nginx 504 Gateway Time-out 請(qǐng)問如何設(shè)置9. index.php錯(cuò)誤,求指點(diǎn)10. 老師 我是一個(gè)沒有學(xué)過php語言的準(zhǔn)畢業(yè)生 我希望您能幫我一下
