传递给组件的绑定(bind)在 html 中工作,但在 Controller 中未定义。
<hero value="foo"></hero>
hero.component.js
import template from './hero.html';
import controller from './hero.controller';
let heroComponent = {
restrict: 'E',
bindings: {
value: '@'
},
template,
controller
};
HeroController.js
class HeroController {
constructor() {
this.name = 'hero';
console.log(this.value); // undefined!
}
}
英雄.html
<section class="hero">
<h1>AngularJs ES6 Example</h1>
<!-- Value is works within template -->
<h3>You can find me inside {{ $ctrl.name }}.html {{ $ctrl.value }}</h3>
</section>
我正在使用 Angular 版本
1.5.0
最佳答案
在构造函数调用期间不太可能解析绑定(bind)。 Angular 内部所做的是实例化 Controller 并在调用构造函数时注入(inject)依赖项。然后,填充绑定(bind)。
您应该使用生命周期 Hook $onInit
或 $onChanges
反而。查看开发者指南 here (关于生命周期钩子(Hook)的相关部分大约在页面的一半处)。
关于AngularJs 1.5 ES6 : bindings undefined in controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40379734/