2015-11-18 17 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> 

が、これはそれを行うための正しい方法であるかどうかを知りたいと思いました。 $ watchの使用を控えたい

ありがとうございます。

答えて

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

関連する問題