1

阅读网络上的各种教程,我遇到了两种不同的注册控制器的方法。

var app = angular.module('myApp', []);

//without explicit dependency injection
app.controller ("myCtrl1", function ($scope, $http) {
       //some implementation
});

//with explicit dependency injection
app.controller ("myCtrl2", ["$scope", "$http", function ($scope, $http) {
       //some implementation
}]);

两者似乎都可以在函数内部使用 $scope 和 $http 对象。

有人可以告诉我这两种方法之间的区别,以及一种方法是否优于另一种方法?如果 Angular 可以找出要注入的正确依赖项,那么显式声明它有什么好处?

4

2 回答 2

3

The issue is minification:

//without explicit dependency injection
a.controller ("myCtrl1", function (b, c) {
       // Broken because toString here returns
       // a, b - which are not dependencies that
       // Angular knows how to resolve
});

//with explicit dependency injection
a.controller ("myCtrl2", ["$scope", "$http", function (b, c) {
       // b and c are properly resolved
}]);
于 2013-08-22T17:13:48.697 回答
1

the main difference is that, with explicit dependency injection, your dependencies are not found based on the arguments names but on the strings you pass. This allows you to use javascript minifiers without risk, because they would rename the arguments.

于 2013-08-22T17:14:00.467 回答