Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  176] [ 2]  / answers: 1 / hits: 53876  / 8 Years ago, tue, july 26, 2016, 12:00:00

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.



Component:



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>


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.



What am I doing wrong?



Here's a plnkr illustrating the problem.


More From » angularjs

 Answers
37

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


[#61249] Friday, July 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yesseniadajab

Total Points: 258
Total Questions: 101
Total Answers: 127

Location: Mexico
Member since Mon, Sep 12, 2022
2 Years ago
;