我尝试使用Angular 1.5和TypeScript 1.8创建一个带控制器的指令,但它不适合我。我看了一堆例子,但是我正在将这些例子用于发球台,它仍然不适合我。我被诅咒了吗?
以下是代码:
export class FooController implements angular.IController {
static $inject = ['myService', '$state'];
constructor(private myService: Services.MyService, private $state: angular.ui.IStateService) {
}
public foo: Services.Dtos.Foo;
public bar;
$onInit() {
if (!this.foo) return;
this.bar = this.$state.href('app.bar', {id: this.foo.id});
}
}
export class FooDirective implements angular.IDirective {
public restrict = 'E';
public replace = true;
public scope = {};
public templateUrl = 'content/templates/foo.template.html';
public controller = FooController;
public controllerAs = 'ctrl';
public bindToController = {
foo: '<',
};
}
FooDirective
上的错误说明如下:
我做错了什么?
更新2017/02/15 IDirective看起来像这样(来自angular.d.ts文件):
interface IDirective {
compile?: IDirectiveCompileFn;
controller?: string | Injectable<IControllerConstructor>;
controllerAs?: string;
/**
* @deprecated
* Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before
* the controller constructor is called, this use is now deprecated. Please place initialization code that
* relies upon bindings inside a $onInit method on the controller, instead.
*/
bindToController?: boolean | {[boundProperty: string]: string};
link?: IDirectiveLinkFn | IDirectivePrePost;
multiElement?: boolean;
priority?: number;
/**
* @deprecated
*/
replace?: boolean;
require?: string | string[] | {[controller: string]: string};
restrict?: string;
scope?: boolean | {[boundProperty: string]: string};
template?: string | ((tElement: JQuery, tAttrs: IAttributes) => string);
templateNamespace?: string;
templateUrl?: string | ((tElement: JQuery, tAttrs: IAttributes) => string);
terminal?: boolean;
transclude?: boolean | 'element' | {[slot: string]: string};
}
答案 0 :(得分:1)
该指令应该是一个返回配置对象的函数。我会写这样的指令:
export const fooDirective = (): angular.IDirective => {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: 'content/templates/foo.template.html',
controller: FooController,
controllerAs: 'ctrl',
bindToController: {
foo: '<'
}
};
};
我还建议您查看新的组件API。它极大地简化了创建新组件的过程,默认情况下它使用了许多最佳实践,例如controllerAs
。
https://docs.angularjs.org/guide/directive
https://docs.angularjs.org/guide/component
答案 1 :(得分:0)
似乎是TypeScript定义只接受布尔值的问题。
export class FooDirective implements angular.IDirective {
public restrict = 'E';
public replace = true;
public scope = {};
public templateUrl = 'content/templates/foo.template.html';
public controller = FooController;
public controllerAs = 'ctrl';
public bindToController:any = {
foo: '<',
};
}
这样可以解决错误,另一方面它赢得了类型检查bindToController。