2015-11-18 7 views
5

पर बटन अक्षम करना मैंने एक निर्देश लिखा है जो 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; 
        }) 
       } 
      } 
     }]) 

एचटीएमएल की तरह है::

<button request-pending="pending" ng-disabled="pending">Save</button> 

पता करने के लिए यह करने का एक सही तरीका है कि क्या चाहता था

यह मेरा निर्देश है। मैं $ घड़ी

का उपयोग करने से बचना चाहता हूं।

उत्तर

2

कोणीय के साथ सामान्य रूप से, कुछ चीजों को करने के लिए कोई विशेष रूप से "कठोर तरीका" नहीं होता है, लेकिन विकल्प हैं।

उदाहरण के लिए, आप सजावट के साथ $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

संबंधित मुद्दे