我写了一条指令,可以在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

谢谢你。

最佳答案

与Angular一样,没有做某些事情的特别“绑定(bind)方法”,但是有很多选择。

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

或者,您也可以利用 $httpProvider.interceptors

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="[email protected]" 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

关于javascript - 在ajax请求时禁用按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33773270/

10-11 23:52