Why are my component bindings undefined in its controller?

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() - 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.

per docs - https://docs.angularjs.org/guide/component


Make sure you use hyphens for bindings in HTML and camelCase for bindings in Javascript.

app.component("test", {
  bindings: {
    "myContactId": "<"
  }
}

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

That's what I always forget to do.


The keyword this doesn't seem to works with arrow function, this works with

controller: function() {
   alert('contact id from controller: ' + this.contactId);
}

When using arrow function, this, seems to refer to the window object because

An arrow function does not create it's own this context, rather it captures the this value of the enclosing context


The value for contactId is available on the $scope in your controller:

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

Link to another version of your Plunker here.