角度控制器显式依赖注入

时间:2013-08-22 17:09:05

标签: angularjs

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

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可以找出要注入的正确依赖项,那么明确声明它有什么好处?

2 个答案:

答案 0 :(得分:3)

问题在于缩小:

//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
}]);

答案 1 :(得分:1)

主要区别在于,通过显式依赖注入,您的依赖关系不是基于参数名称而是基于您传递的字符串。这允许您在没有风险的情况下使用javascript minifiers,因为它们会重命名参数。

相关问题