为什么我的组件绑定在其控制器中未定义? [英] Why are my component bindings undefined in its controller?

查看:116
本文介绍了为什么我的组件绑定在其控制器中未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个简单的角度组件。我将参数作为绑定传递并在屏幕上显示其值。一切正常:我可以看到屏幕上显示的参数。

I'm writing a simple angular component. I'm passing a parameter as a binding and display its value on the screen. All works fine: I can see the parameter being displayed on the screen.

组件:

var app = angular.module("test", []);
app.component("test", {
  bindings: {
    "contactId": "<"
  },
  controllerAs: "model",
  controller: () => {
    //output: 'contact id from controller: undefined'
    console.log(`contact id from controller: ${this.contactId}`);
  },
  template: "<div>Contact id from view: {{model.contactId}}</div>"
});

Html:

<test contact-id="8"></test>

但是,当我尝试从控制器中访问绑定时(请参阅console.log),绑定值为 undefined 。我不明白它在视图中是如何可用的,但不是在控制器中。

However, when I try to access the binding from within the controller (see the console.log), the binding value is undefined. I don't understand how it can be available in the view, but not in the controller.

我做错了什么?

这是一个 plnkr 来说明问题。

推荐答案

使用angular的组件时,控制器尚未通过内部链接连接。如果您尝试在控制器的构造函数中执行此操作,则尚未将链接绑定到绑定。 Component API公开了一些你可以定义的生命周期钩子,它会在特定时间触发。你正在寻找 $ onInit 钩子。

When using angular's components, there is a point where the controller hasn't been wired up via the internal linking. If you're trying to do this in the constructor of your controller, you haven't been linked to the bindings. The Component API exposes a few life-cycle hooks that you can define that will fire at certain times. You're looking for the $onInit hook.


$ onInit() - 在构造了元素上的所有控制器并初始化它们的绑定之后(以及在该元素上的指令的前置和后置链接函数之前),在每个控制器上调用。这是为您的控制器放置初始化代码的好地方。

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

每个文档 - https://docs.angularjs.org/guide/component

这篇关于为什么我的组件绑定在其控制器中未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆