gpt4 book ai didi

javascript - ajax 调用结束并返回新数据时如何阻止或处理用户输入

转载 作者:行者123 更新时间:2023-11-28 01:37:05 26 4
gpt4 key购买 nike

我的 Angular 应用程序有一个保存调用,它将数据保存到数据库并将保存的数据返回到模型,以便模型在保存后重新填充最新的数据。我目前面临的问题是,在保存时,模型可能会发生变化。例如,如果保存调用需要 2 秒才能完成,然后将数据加载回来,那么在这 2 秒的时间间隔内,用户将继续将表单数据键入到绑定(bind)到模型的表单中。当来自服务器的模型重新加载时,表单将丢失在保存起始点和完成点之间键入的数据。

有什么好的建议可以避免这个问题吗?

最佳答案

最简单的解决方案就是在通话结束时隐藏/禁用输入(这应该非常简短)。您可以简单地使用 ng-disabled="callIsOut"ng-hide="callIsOut" 等标志变量。

如果您确实需要它们能够同时输入数据,那么您没有理由不将当前用户输入与新接收的数据进行比较,并替换接收到的数据对象中的用户数据。

以下是一些示例代码: Live demo (click).

<h1>Update</h1>
<input type="text" ng-model="otherInput">
<span ng-show="callIsOut">Saving...</span>
<button ng-click="otherSave()">Save</button>

<hr>

<h1>Disable</h1>
<input type="text" ng-model="myInput" ng-disabled="callIsOut">
<span ng-show="callIsOut">Saving...</span>
<button ng-click="save()">Save</button>

<hr>

<h1>Hide</h1>
<input type="text" ng-model="myInput" ng-hide="callIsOut">
<span ng-show="callIsOut">Saving...</span>
<button ng-click="save()">Save</button>

JavaScript:

app.controller('myCtrl', function($scope, myService) {
$scope.callIsOut = false;

$scope.save = function() {
$scope.callIsOut = true;
myService.save($scope.myInput).then(function(data) {
$scope.myInput = data;
$scope.callIsOut = false;
});
$scope.myInput = '';
};

$scope.otherSave = function() {
$scope.callIsOut = true;
myService.save($scope.otherInput).then(function(data) {
if ($scope.otherInput === '') {
$scope.otherInput = data;
}
$scope.callIsOut = false;
});
$scope.otherInput = '';
};
});

关于javascript - ajax 调用结束并返回新数据时如何阻止或处理用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21419376/

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