簡體   English   中英

在ajax請求時禁用按鈕

[英]disabling button while ajax request

我寫了一個指令,它有助於在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一樣,做某些事情沒有特別“嚴格的方法”,但有一些選擇。

例如,您可以使用裝飾器擴展$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM