我有一个视图,需要在单击按钮时进行ajax调用。在处理请求期间,如果用户不必要地单击,我不希望请求堆积。为了阻止多个请求,我进行了以下设置。
视野中
<button ng-click="getBooks()"></button>
Run Code Online (Sandbox Code Playgroud)
在控制器中
var ajaxInProgress = false;
$scope.getBooks = function () {
if (ajaxInProgress) {
return false;
}
ajaxInProgress = true;
BooksFactory
.getBooks()
.then(function (response) {
ajaxInProgress = false;
})
.catch(function() {
ajaxInProgress = false;
});
};
Run Code Online (Sandbox Code Playgroud)
这对我来说效果很好,但是将其添加到同一视图中的多个此类函数中时,控制器开始变得混乱。有没有更好的解决方案来清理这个烂摊子?
您可以使用范围变量并将其绑定到ng-disabled。这可以防止在作用域函数开始时出现额外的情况:
鉴于:
<button ng-click="getBooks()" ng-disabled="inProgress"></button>
Run Code Online (Sandbox Code Playgroud)
在控制器中:
$scope.inProgress = false;
$scope.getBooks = function () {
$scope.inProgress = true;
BooksFactory
.getBooks()
.then(function (response) {
// do something with response;
})
.catch(function() {
// error handling
})
.finally(function() {
$scope.inProgress = false;
})
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2077 次 |
| 最近记录: |