在ajax请求时禁用按钮

时间:2015-11-18 06:33:45

标签: javascript angularjs ajax angular-directive

我编写了一个指令,有助于在ajax请求待处理时禁用按钮。

这是我的指示:

.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>

想知道这是否是一种正确的做法。 我想不要使用$ watch

谢谢。

1 个答案:

答案 0 :(得分:2)

与Angular一样,没有特别的&#34;严格的方式&#34;做某些事情,但也有选择。

例如,您可以使用装饰器扩展$http服务并使用自定义事件。

或者你也可以利用$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