disabling button while ajax request

a 夏天 提交于 2019-12-05 12:17:18

As usual with Angular, there is no particularly "rigt way" to do certain things, but there are options.

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

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>

Plunker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!