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
};