我正在使用 angularjs 1.5.8 和 TypeScript 2.0.6。 考虑以下 tsconfig.json 和 Angular 组件:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5"
}
}
和组件:
var app = angular.module('App', []);
class testComponent {
public message: string = "worked!";
}
app.component('ctrl', {
bindings: {
message: '<'
},
template: '<div>Hello {{vm.message}}</div>',
controller: testComponent,
controllerAs: "vm"
});
它工作正常,直到我将目标更改为“es6”,但它没有按预期工作,我在不更改代码的情况下获得了两个不同的结果。 在 es6 中,“消息”属性将为空。
以下代码适用于两种配置:
app.component('ctrl', {
bindings: {
message: '<'
},
template: '<div>Hello {{vm.message}}</div>',
controller: function () {
this.message = 'test';
},
controllerAs: "vm"
});
这里出了什么问题?
最佳答案
简而言之,当使用构造函数实例化指令 Controller 时,Angular 在调用构造函数之前(神奇!) 我们应该使用 $onInit 而不是像这样的构造函数
public $onInit() {
this.message = 'worked!';
}
关于javascript - Angular 1.5.8 组件与 typescript (ecma6) 和 (ecma5) 配置不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633525/