AngularJS控制器无法正确调用函数

时间:2017-12-21 17:28:30

标签: javascript angularjs this

我正在使用Angular 1.6并且在尝试让控制器调用我传入的函数时遇到了麻烦。在下面的示例中,我有homepage.html将函数传递给<image-selector>。我希望<image-selector>调用传入函数,该函数将在图像更改后更新父函数。然后,HomepageCtrl会调用自己的函数updateState()来处理数据。

问题是HomepageCtrl无法调用updateState(),因为this.updateState()中的onImageChange()未定义。我怀疑是因为ImageSelectorCtrl正在调用onImageChange()而导致问题,因此this指向ImageSelectorCtrl而不是HomepageCtrl

我想知道如何解决此问题,以便ImageSelectorCtrl可以调用onImageChange(),然后调用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 个答案:

答案 0 :(得分:1)

请尝试将此绑定到您的类方法,因为它们在不同的上下文中执行。

 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...');
    }
}