Shutdown button when ajax request

I wrote a directive that would help disable the button while awaiting ajax requests.

this is my directive:

.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 is like:

 <button request-pending="pending" ng-disabled="pending">Save</button> 

I wanted to know if this was done correctly. I want to refrain from using $ watch

Thanks.

+5
source share
1 answer

As usual, with Angular there is no particular "hard way" to perform certain actions, but there are options.

For example, you can extend the $http service with a decorator and go with custom events.

Or you can also use $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> 

Plunker

+2
source

Source: https://habr.com/ru/post/1236209/


All Articles