2015-11-18 23 views
5

Tôi đã viết một chỉ thị có thể giúp vô hiệu hóa một nút trong khi yêu cầu ajax đang chờ xử lý.nút vô hiệu hóa trong khi yêu cầu ajax

đây là chỉ thị của tôi:

.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 giống như:

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

Muốn biết liệu đây là một cách đúng để làm việc đó. Tôi muốn không sử dụng $ watch

Cảm ơn bạn.

Trả lời

2

Như thường lệ với Góc, không có cách đặc biệt "cứng nhắc" để làm những việc nhất định, nhưng có các tùy chọn. Ví dụ:

Ví dụ: bạn có thể mở rộng dịch vụ $http với trang trí và đi kèm với sự kiện tùy chỉnh.

Hoặc bạn cũng có thể tận dụng $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

Các vấn đề liên quan