AngularJs 1.5 ES6 : bindings undefined in controller

标签 angularjs es6-class angular-components

传递给组件的绑定(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/

相关文章:

javascript - 将参数传递给解析函数

php - 如何一起使用 laravel 和 angularjs 路由?

css - AngularJS - 从多个选项更改 1 <div> 上的多个 CSS 类

javascript - 在 Javascript ECMAScript 6 中从类名创建对象

angular - 为什么不会调用 ngOnChanges 钩子(Hook)?

dart - Dart Angular-在手机上获取滑动事件

javascript - 使用 Angular js 将 FormData 文件与模型数据一起发布

javascript - 用 Babel 扩展 MediaSource ——如何正确调用 super()?

javascript - ecmascript 6 如何通过反射调用静态类方法

angular - 启用 Angular 组件以显示多个表格行而不破坏表格格式