【问题标题】:AngularJS Dependency Injection Fails in moduleAngularJS依赖注入在模块中失败
【发布时间】:2016-04-25 00:52:28
【问题描述】:

我对角度依赖注入机制有疑问。 我在一个独立模块中编写了一个指令,它在数据表上做了一些巧妙的事情。我正在使用 TypeScript,我的指令如下所示:

export class MdListControls implements angular.IDirective {
  public templateUrl = "/app/templates/mdListControls.html";
  public static instance(): any {
    return new MdListControls();
  };

  public restrict = 'E';
  public transclude = true;
  public replace = true;
  public scope = {
    grid: '=',
  };
  public controller = "mdListControlsController"
  public controllerAs = "vm";

  public link = function (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) {

  };
}

我的控制器看起来像这样:

export class MdListControlsController { 
  static $inject = ['scope']
  constructor($scope: angular.IScope){
    //Setup the constructor
  }
  //Here goes the controller Logic
}

我正在一个新模块中注册指令和控制器,如下所示:

angular.module("base.directives.mdListControls", [])
  .controller("mdListControlsController", MdListControlsController)
  .directive("mdListControls", function () { return MdListControls.instance() });

但是,一旦我运行应用程序,一旦加载指令,我就会收到以下错误:

Argument 'mdListControlsController;' is not a function, got undefined

起初这看起来不像是依赖注入的问题。但是当我在应用程序本身(被注入“base.directives.mdListControls”模块)上注册控制器时

app.controller("mdListControlsController", MdListControlsController);  

一切正常,控制器被正确注入指令。

有谁知道我在这里做错了什么? 感谢您的帮助!

【问题讨论】:

  • 我不知道 TypeScript 但问题是 JS 执行的顺序。当您的控制器注册为 angular.module("base.directives.mdListControls", []) .controller("mdListControlsController", MdListControlsController) 时,MdListControlsController 不可用
  • 我也不知道 TypeScript。如果在控制器声明中执行 .controller("mdListControlsController", function () { return MdListControlsController }) 会发生什么?
  • 也许是个愚蠢的问题。但是您似乎导出了 MdListControlsController。您是否还在指令模块文件的顶部导入它?
  • @DaanvanHulst:MdListControls 和 MdListControlsController 类都位于同一个 typescript 命名空间中,因此我不需要导入它。

标签: javascript angularjs dependency-injection typescript


【解决方案1】:

在您的 MdListControls 类中尝试提供控制器类,而不是控制器名称。

...    
public scope = {
    grid: '=',
  };
public controller = MdListControlsController
public controllerAs = "vm";
...

【讨论】:

  • 感谢您的提示。这显然有效,因为“注入”知道发生在 TypeScript 级别。但是现在 angular 根本没有依赖注入。但是,我想我必须采用那个解决方案。
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 2015-10-06
  • 2017-09-16
  • 2015-07-21
  • 2012-08-13
相关资源
最近更新 更多