禁用按钮时的Ajax请求 [英] disabling button while ajax request
本文介绍了禁用按钮时的Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个指令,这将有助于禁用按钮,同时AJAX请求正在等待。
I have written a directive which would help disabling a button while ajax requests are pending.
这是我的指令:
.directive('requestPending', ['$http', function ($http) {
return {
restrict: 'A',
scope: {
'requestPending': '='
},
link: function (scope, el, attr) {
scope.$watch(function () {
return $http.pendingRequests.length;
}, function (requests) {
scope.requestPending = requests > 0;
})
}
}
}])
的HTML是这样的:
<button request-pending="pending" ng-disabled="pending">Save</button>
想知道这是否是做了一个正确的方式。 我想利用$手表不要
Wanted to know whether this is a right way of doing it. I want to refrain from using $watch
感谢你。
推荐答案
像往常一样与棱角分明,没有特别rigt办法做某些事情,但有选择。
As usual with Angular, there is no particularly "rigt way" to do certain things, but there are options.
例如,你可以扩展 $ HTTP
带装饰服务,去与自定义事件。
For instance, you can extend $http
service with a decorator and go with custom events.
或者,你也可以利用 $ httpProvider.interceptors
。
Or you can also leverage $httpProvider.interceptors
.
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
angular
.module('app', [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push(function ($rootScope) {
var activeRequests = 0;
return {
request: function (config) {
$rootScope.pending = true;
activeRequests++;
return config;
},
response: function (response) {
activeRequests--;
if(activeRequests === 0) {
$rootScope.pending = false;
}
return response;
}
}
});
})
.controller('appCtrl', function($scope, $http) {
$scope.makeRequestOne = function() {
$http
.get('https://httpbin.org/delay/2')
.then(function(response) {
$scope.responseOne = response.data;
});
};
$scope.makeRequestTwo = function() {
$http
.get('https://httpbin.org/delay/4')
.then(function(response) {
$scope.responseTwo = response.data;
});
};
});
</script>
</head>
<body ng-controller="appCtrl">
<h1>Hello Plunker!</h1>
<button
ng-click="makeRequestOne()"
ng-disabled="pending">Request One</button>
<button
ng-click="makeRequestTwo()">Request Two</button>
<hr>
<pre>{{ responseOne }}</pre>
<pre>{{ responseTwo }}</pre>
</body>
</html>
这篇关于禁用按钮时的Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文