在ajax请求时禁用按钮

Soh*_*are 5 javascript ajax angularjs 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;
                    })
                }
            }
        }])
Run Code Online (Sandbox Code Playgroud)

HTML就像:

<button request-pending="pending" ng-disabled="pending">Save</button>
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

sbe*_*lin 2

与 Angular 一样,没有特别“正确的方法”来做某些事情,但有一些选择。

例如,您可以$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>
Run Code Online (Sandbox Code Playgroud)

普朗克