列出注入的依赖项

Nic*_*lle 7 javascript angularjs angularjs-controller angularjs-module

有没有办法知道哪些依赖项被注入我的Angular模块?

angular.module('myModule', [
  'ui.bootstrap'
])
.controller('myController', [function () {
  // var dependencies = Magic.dependencies;
  // console.log(dependencies);
}]);
Run Code Online (Sandbox Code Playgroud)

scn*_*iro 2

在你的控制器中,如果你注入$window,你可以挖掘依赖关系,具体来说,.requires你的模块上存在一个。为此,您可以将您的模块声明为全局模块var,以便我们可以在我们的 上找到它$window,在本例中,让我们调用它app- 或者 - 您可以绕过全局变量并直接$window调用angular.module('myModule').requires

  • ngRoute还添加了证明可发现的依赖项数组。


var app = angular.module('myModule',
[
    'ui.bootstrap',
    'ngRoute'
]).controller('ctrl', ['$scope', '$window', function($scope, $window) {
    console.log($window.app.requires) // ["ui.bootstrap", "ngRoute"]
    console.log(angular.module('myModule').requires) // without global - $window not needed
}]);
Run Code Online (Sandbox Code Playgroud)

JSFiddle 链接- 工作示例


注意 - 如果利用全局变量,您可以简单地调用windowwindow.app.requires- 无需注入$window。但是,请参阅AngularJS $window 文档以了解为什么$window首选。