prevent multiple form submissions using angular.js - disable form button

后端 未结 9 735
耶瑟儿~
耶瑟儿~ 2020-12-13 21:22

I want to prevent multiple form submissions using angular.js. The question is related to this question.

When the user clicks on a form submit button the value / labe

9条回答
  •  自闭症患者
    2020-12-13 21:50

    Here is a general way to do it for all AJAX requests using $http interceptors. If you have all of your REST routes starting from /api/ then:

         angular.module('yourapp').factory('loadingInterceptor',['$q','$rootScope',function($q,$rootScope) {
             var apiRe = /^\/api\//;
        return {
            request: function(config) {
                if (config.url.match(apiRe)) {
                    $rootScope.loading = true;
                }
                config.headers = config.headers || {};
    
                return config;
            },
            response: function(res) {
                $rootScope.loading = false;
                return $q.resolve(res);
            },
    
            'responseError': function(rejection) {
                $rootScope.loading = false;
                return $q.reject(rejection);
            }
        };
    }]);
    
    
    angular.module('yourapp').config(['$httpProvider', function($httpProvider) {
        $httpProvider.interceptors.push('loadingInterceptor');
    }]);
    

    Using interceptor you won't have to put $scope.isLoading in each controller. The downside is that any button with ng-disabled="loading" will be blocked during request.

提交回复
热议问题