【问题标题】:Sharing directive isolated scope with dynamic controller与动态控制器共享指令隔离范围
【发布时间】:2015-12-13 18:42:12
【问题描述】:

我正在编写一个 TypeScript AngularJS 应用程序并且碰壁了。我需要动态地将控制器应用于指令,因为该指令提供了一个动态 UI 来适应不同的任务。我需要能够在控制器中动态替换以处理指令中的不同活动。

我在How to set the dynamic controller for directives? 找到了回答如何执行此操作的信息,并提供以下信息:

export interface IHostScope extends ng.IScope {
  type: string;
  title: string;
  subtitle: string;
}

export class Host implements ng.IDirective {
  public templateUrl: "/some/template/url";
  public restrict: "E";
  public replace: true;
  public controller = "@";
  public name = "controllerName";
  public scope: Object {
    type: "@",
    title: "@",
    subtitle: "@"
  };
  public link: Function = (scope: IHostScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes): void => {
    //Stuff happens in here
  }
}

export class ControllerA {
  constructor(private: $scope: IHostScope, private $state: ng.ui.IStateService) {
    //$scope and $state are null at runtime
  }
}


module.directive("host", <any>Host);
module.controller("ControllerA", ControllerA);

问题在于,在运行时,$state 和 $scope 值为 null,我无法访问这些变量中的每一个可能已由指令上的链接函数设置的现有属性。如何在指令和动态控制器之间共享范围并让 $state 实际填充?

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    当然,我一发布这个,就意识到答案很简单。我需要将服务注入控制器并自行解决。

    在 ControllerA 的顶部,在构造函数之前添加 $inject 语句,如下所示:

    export class ControllerA {
      static $inject = ["$scope", "$state"];
      constructor(private $scope: IHostScope, private $state: ng.ui.IStateService) {
        //Do stuff - works like a charm
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多