Lock button until function is completed AngularJs

1

I need a way to lock a button until the ng-click is completed, to prevent the user from clicking the button again, thinking that nothing happened or anything.

Is there any good way to do this, using directives to something like this?

    
asked by anonymous 30.08.2018 / 15:09

2 answers

3

A simple way to do this:

<button ng-click="save()" ng-disabled="isProcessing">Save</button>


$scope.save = function(){
  $scope.isProcessing = true;
  $http.post('localhost', data).success(
    $scope.isProcessing = false;
  );
}
    
30.08.2018 / 15:27
2

As a complement to Otto's answer, I suggest you use finally instead of then , because if a failure occurs, the variable that indicates loading will be locked "forever."

I would do so:

<button ng-click="save()" ng-disabled="isProcessing">Save</button>


$scope.save = function(){
  $scope.isProcessing = true;
  $http.post('localhost', data)
  .finally(function () {
      $scope.isProcessing = false;
  })
 .then(function (response) {
      $scope.resposta = response.data;
  })
}

The finally is always executed at the end of the request, regardless of whether it has failed or not.

    
30.08.2018 / 15:37