4

bindings passed to component works in html, but undefined in 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!
  }
}

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

I am using angular version 1.5.0

2 Answers 2

3

It is unlikely that bindings are resolved during the constructor call. What angular internally does is instantiate the controller and inject dependencies on calling the constructor. Then, bindings are populated.

You should use the life-cycle hooks $onInit or $onChanges instead. Have a look at the developer guide here (the relevant section about life-cycle hooks is about half way down the page).

Sign up to request clarification or add additional context in comments.

3 Comments

i tried in $onInit, but it is still undefined, my value will not change so i don't see a point to use $onChanges
@farhanlatheef 1.5.0 doesn't have $onInit, as I remember. Upgrade it to at least 1.5.3.
$onInit should be there in 1.5.0. However, you are correct $onChanges came with 1.5.3. Could you provide a plunkr outlining your problem? Is foo a defined property of the parent controller?
3

its is undefined because value was loaded after an api call, using ng-if solved the problem

<hero ng-if="$ctrl.value" value="$ctrl.value"></hero>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.