2015-11-18 40 views
5

我寫了一個指令,可以在ajax請求未決時幫助禁用按鈕。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> 

想知道這是否是做的正確的方式。 我想避免使用$手錶

謝謝。

回答

2

和往常一樣,Angular沒有特別的「方式」去做某些事情,但是也有選擇。

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