Why are my component bindings undefined in its controller?

前端 未结 9 1787
醉梦人生
醉梦人生 2021-01-31 13:22

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 th

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 13:46

    There are two problems with the code causing the "undefined" error.

    1. As stated above the $onInit lifecycle hook should first be reached, the onInit is fired when all bindings have been made.

    From the official documentation:AngularJs Documentation

    $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.

    1. The second problem you will likely have, is that your controller will not reach the lifecyclehook when using "() =>" arrow notation as a parameter for the controller function.

    The problem being is that arrow notation won't have it's own scope, but rather use it's enclosing scope. Meaning that when using "this" will refer to the window object rather than the component. So calling this.$onInit() will be called on the window, and will not be fired, because it doesn't exist on the window.

提交回复
热议问题