我正在编写一个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,我无法访问可能由指令上的link函数设置的每个变量的现有属性。如何在指令和动态控制器之间共享范围并获得$ state实际填充?
答案 0 :(得分:0)
当然,只要我发布这个,我意识到答案很简单。我需要将服务注入控制器并自行解决。
在构造函数之前在ControllerA的顶部添加$ inject语句,如:
export class ControllerA {
static $inject = ["$scope", "$state"];
constructor(private $scope: IHostScope, private $state: ng.ui.IStateService) {
//Do stuff - works like a charm
}
}