0

I am using Angular 1.6 and am having trouble trying to get a controller to call a function I have passed in. In my example below, I have homepage.html which is passing a function into <image-selector>. I want <image-selector> to call the passed-in function which will update the parent when the image has been changed. HomepageCtrl will then call its own function updateState() to process the data.

The problem is that HomepageCtrl fails to call updateState() because this.updateState() in onImageChange() is undefined. I suspect that the issue is caused because ImageSelectorCtrl is invoking onImageChange() so this is pointed to the ImageSelectorCtrl instead of HomepageCtrl.

I am wondering how I would fix this issue so ImageSelectorCtrl can invoke onImageChange() which will then call updateState()?

// homepage.js
import homepageHtml from './homepage.html';
class HomepageCtrl {
    constructor() {
    }

    onImageChange(newImage) {
        this.updateState({newImage: processImage(newImage)}); // console error: cannot read property of 'updateState' of undefined
    }

    updateState(options) {
        console.log('Updating state...');
    }
}
export const Homepage = {
    template: homepageHtml,
    controller: HomepageCtrl
};


// homepage.html
<div class="homepage">
    <image-selector on-change="$ctrl.onImageChange"></image-selector>
</div>


// imageSelector.js
import imageSelectorHtml from './image-selector.html';
class ImageSelectorCtrl {
    constructor() {
        this.imageUrl;
    }

    onChange() {
        this.onChange()(imageUrl);
    }
}
export const ImageSelector = {
    bindings: {
        onChange: '&'
    },
    template: imageSelectorHtml,
    controller: ImageSelectorCtrl
};

1 Answer 1

1

please try binding this to your class methods as they are being executed in a different context.

 class HomepageCtrl {
    constructor() {
      this.onImageChange = this.onImageChange.bind(this)
      this.updateState = this.updateState.bind(this)
    }

    onImageChange(newImage) {
        this.updateState({newImage: processImage(newImage)}); // console error: cannot read property of 'updateState' of undefined
    }

    updateState(options) {
        console.log('Updating state...');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.