【问题标题】:Angular call function in foreachforeach中的角度调用函数
【发布时间】:2017-12-30 12:10:51
【问题描述】:

在我的组件中,我有一个在选择客户端时触发的 foreach 循环。在这个循环中,我必须在同一个组件中调用一个函数。

为此,我必须使用 this.functionName() 来调用该函数。但显然这在 foreach 循环中不起作用,因为“this”不再是组件本身。

有人对此有解决方案吗?

this.clientService.selectedClient.forEach(function(client) {
    this.getIntake(); // not working
});

【问题讨论】:

    标签: javascript angularjs angular foreach


    【解决方案1】:

    使用箭头函数

    this.clientService.selectedClient.forEach((client) => {
        this.getIntake(); // not working
    });
    

    否则this不会指向本地类实例

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    【讨论】:

    • 如此简单的解决方案!谢谢。
    • 也可以将组件作为函数作用域传递:developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions(参见词法本部分)
    • @brk,肯定会的。
    • @MartineMulder - 如果它解决了您的问题,请不要忘记将答案标记为已接受(带有绿色复选标记)。
    猜你喜欢
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多