angularjs - Angular 依赖注入(inject) - 我一直看到两种不同的方法

标签 angularjs dependency-injection

有时我看到 Angular 中的依赖注入(inject)是这样的:

angular.module('controllers')
  .controller('BooksListCtrl', ['$scope', 'Books', function($scope, Books){
    Books.get(function(data){
      $scope.books = data;
    });
  }]);

有时它看起来像下面没有数组,只是将依赖项直接传递给函数:
angular.module('controllers')
  .controller('BooksListCtrl', function($scope, Books){
    Books.get(function(data){
      $scope.books = data;
    });
  });

一种方法是正确的吗?这是否取决于您是否对 Controller 、指令和等进行依赖注入(inject)?

最佳答案

Sometimes I see dependency injection in Angular done like:

angular.module('controllers')
  .controller('BooksListCtrl', ['$scope', 'Books', function($scope, Books){
    Books.get(function(data){
      $scope.books = data;
    });
  }]);

And sometimes it looks like the following without the array, and just passing dependencies directly into the function:

angular.module('controllers')
  .controller('BooksListCtrl', function($scope, Books){
    Books.get(function(data){
      $scope.books = data;
    });
  });


哪一个是正确的方法?

两个都

这是否取决于您是否对 Controller 、指令和等进行依赖注入(inject)?



那么它们有什么不同呢?

那么第一种形式使您可以自由地使用您自己的自定义名称来处理依赖项。例如
app.controller('BooksListCtrl', ['$scope', 'Books', function($scope, myOwnBookName){
    myOwnBookName.get(function(data){
      $scope.books = data;
    });
}]);

而第二个没有..但两者都是正确的。

此外,您在使用第一种形式时需要小心一点,因为您可能会错误地跳过依赖项和/或将其与错误的依赖项链接。
例如做类似的事情:
app.controller('BooksListCtrl',['$scope','$window','$rootScope', function(foo, bar){
 ...
}]);

会极具破坏性,因为 foo现在将指向 $scope , bar将指向 $window$rootScope将是 undefined .只需保持顺序不变并遵循正确的命名约定。

关于angularjs - Angular 依赖注入(inject) - 我一直看到两种不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31406387/

相关文章:

java - spring Autowiring 上的 NullPointerException

python - django View 中的依赖注入(inject)

angularjs - Sinatra + Angularjs 路由

javascript - javascript 文件中的 Angular 分割 json

c# - 需要帮助了解 Ninject 如何将 Nhibernate SessionFactory 实例放入 UnitOfWork 中?

asp.net-web-api - 统一容器 : what is default lifetimemanager

javascript - 如何在 AngularJS 中启用数据网格?

html - AngularJS 显示 MongoDB 数据

jquery - ngRoute 在页面之间随机切换

GWT-GIN 多种实现?