Angularjs 带控制器的Angular 1.5+TypeScript指令
我正在尝试使用Angular 1.5和TypeScript 1.8创建一个控制器指令,但它对我不起作用。我看了很多例子,但我一直在关注这些例子,但这对我来说仍然不起作用。我被诅咒了吗 代码如下:Angularjs 带控制器的Angular 1.5+TypeScript指令,angularjs,typescript,Angularjs,Typescript,我正在尝试使用Angular 1.5和TypeScript 1.8创建一个控制器指令,但它对我不起作用。我看了很多例子,但我一直在关注这些例子,但这对我来说仍然不起作用。我被诅咒了吗 代码如下: export class FooController implements angular.IController { static $inject = ['myService', '$state']; constructor(private myService: Services.M
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: '<',
};
}
指令应该是返回配置对象的函数。我会这样写指令:
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
似乎是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。我将您的代码复制粘贴到一个角度项目中,没有收到错误。你用什么打字?请把它们加到你的问题中。@Sabastin,我加上了打字。这让我很困惑。我不知道为什么它不起作用。根据这一点:解决方案是显式地将scope和bindToController强制转换为{[boundProperty:string]:string},错误就会消失。这个答案根本没有帮助。问题是TypeScript正在抱怨我的bindToController不正确。我不确定发生了什么。您不需要将单词public写7次,它对您的代码没有影响,除非它降低了可读性。@AluanHaddad,这取决于tslint设置。
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: '<',
};
}