【问题标题】:List dependencies injected列出注入的依赖项
【发布时间】:2015-08-26 01:24:36
【问题描述】:

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

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

【问题讨论】:

    标签: javascript angularjs angularjs-controller angularjs-module


    【解决方案1】:

    在你的控制器中,如果你注入$window,你可以挖掘依赖,具体来说,你的模块上有一个.requires。为此,您可以将您的 module 声明为全局 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
    }]);
    

    JSFiddle Link - 工作示例


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

    【讨论】:

      【解决方案2】:

      @salniro's answer 为基础,您不需要全局变量或$window

      依赖项列在angular.Module.requires 属性中:

      angular.module('myModule', [
          'ui.bootstrap',
          'ngRoute'
      ])
      .controller('ctrl', function() {
          var app = angular.module('myModule');
          console.log(app.requires); // ["ui.bootstrap", "ngRoute"]
      });
      

      http://jsfiddle.net/8vtf6gar/1/

      【讨论】:

      • 扎克感谢您的反馈。我已经用你的发现更新了我的答案,因为这是一个次要的选择。我也感谢您对此进行调查
      • 当然可以。感谢您提供答案!从来不知道这是可能的
      猜你喜欢
      • 2020-12-20
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      相关资源
      最近更新 更多