gpt4 book ai didi

javascript - v2.canGoForward 不是函数

转载 作者:行者123 更新时间:2023-12-03 05:20:12 25 4
gpt4 key购买 nike

我正在尝试将代码 vm.canGoForward 从我的 Controller 移动到服务以隐藏实现细节。

代码更改之前

这工作得很好。

查看:

<button ng-disabled="!vm.canGoForward()" class="btn btn-primary" name="next" type="button" ng-click="vm.gotoStep(vm.currentStep + 1)">

Controller :

var vm = this;
vm.currentStep = 1;
vm.steps = WizardService.getWizardSteps(vm.formData);

vm.canGoForward = function() {
var res = true,
i,
nextStateIndex = vm.currentStep + 1;

if (nextStateIndex > vm.steps.length) {
return false;
}
for (i = 1; res && i <= nextStateIndex; i++) {
res = (res && vm.steps[i-1].isReady());
}

return !!res;
};

服务

var wizardService = {
getWizardSteps: getWizardSteps
};
return wizardService;

function getWizardSteps(formData) {
var wizardSteps = [
{
step: 1,
name: 'Name',
template: 'views/wizard/step1.html',
isReady: function() { return true; }
},
{
step: 2,
name: 'Email',
template: 'views/wizard/step2.html',
isReady: function() { return formData.firstName && formData.lastName; }
},
{
step: 3,
name: 'Job Category',
template: 'views/wizard/step3.html',
isReady: function() { return formData.email; }
}
];
return wizardSteps;
}

代码更改后

查看

保持不变

Controller

var vm = this;
vm.currentStep = 1;
vm.steps = WizardService.getWizardSteps(vm.formData);
vm.canGoForward = WizardService.canGoForward(vm.currentStep, vm.steps);

服务

var wizardService = {
getWizardSteps: getWizardSteps,
canGoForward: canGoForward
};
return wizardService;

function getWizardSteps(formData) {
var wizardSteps = [
{
step: 1,
name: 'Name',
template: 'views/wizard/step1.html',
isReady: function() { return true; }
},
{
step: 2,
name: 'Email',
template: 'views/wizard/step2.html',
isReady: function() { return formData.firstName && formData.lastName; }
},
{
step: 3,
name: 'Job Category',
template: 'views/wizard/step3.html',
isReady: function() { return formData.email; }
}
];
return wizardSteps;
}

function canGoForward(currentStep, steps) {
console.log(steps);

var res = true,
i,
nextStateIndex = currentStep + 1;

if (nextStateIndex > steps.length) {
return false;
}
for (i = 1; res && i <= nextStateIndex; i++) {
res = (res && steps[i-1].isReady());
}

return !!res;
}

我现在收到以下错误:TypeError:v2.canGoForward 不是函数。我该如何解决?

最佳答案

在您的第二个版本中,以下行实际上会当场调用 WizardService.canGoForward,而不是分配它:

vm.canGoForward = WizardService.canGoForward(vm.currentStep, vm.steps);

分配的是该调用的返回值,这显然不是一个函数,因此稍后尝试调用时会出现错误消息。

如果您想分配该函数,并确保稍后调用该函数时传递参数,请使用bind:

vm.canGoForward = WizardService.canGoForward.bind(WizardService, vm.currentStep, vm.steps);

关于javascript - v2.canGoForward 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com