0

i've seen many posts about this subject, but not specificly about this question.

I'm wondering if there could be a generic directive/controller in AngularJs to disable a button (that calls an ajax request) and re-enable it after the request ends.

I've used the word "generic" because i've seen some solutions using a callback after a specific ajax request, but it's not what i need.

I need that: when clicking on a button, and the button calls an ajax request, it becomes disabled until the request ends.

Thank you for your help

1 Answers1

0

Here is a possibility.

You can think of http service calls just as a promise. Once a http service call is fulfilled then it will call the next promise in the chain, if there is one.

You can receive a funcion in a directive, then do a wrapping call to it and chain another function to it. So this way you know when the promise is being executed and when it's fulfilled.

You need to be sure to retun the promise in the controller. Then pass that funcion to the directive.

Check the following example

https://codepen.io/bbologna/pen/zdpxoB

JS

var app = angular.module('testApp', []);

app.factory('fakeHttpService', ['$timeout', function($timeout){
  var doSomething = function(value) {
    return new Promise(function(resolve, reject) {
        $timeout(() => { resolve(value + 1); $timeout() }, 1000);
        })
    }
  return { doSomething: doSomething }
}])

app.controller('sampleController', ['$scope', 'fakeHttpService', 
    function($scope, fakeHttpService) {
        $scope.doSomething = function(value){
        return fakeHttpService.doSomething(value);
    }
    }
])

app.directive('buttonAsync', function(){
    return {
    restrict: 'E',
    template: `<button ng-click="excecute()" ng-disabled="disabled">DO</button>`,
    scope: {
        on : '&'
    },
    controller : ['$scope', function($scope) {
        $scope.disabled = false;
        $scope.excecute = function() {
        $scope.disabled = true;
        $scope.on()
            .then(function() {
            $scope.disabled = false;
          })
      }
    }]
  }
})

Html

<div ng-app="testApp" ng-controller="sampleController">
  <button-async on="doSomething(3)"></button-async>
</div>
bruno.bologna
  • 475
  • 4
  • 14