Lock button until Function is completed Angularjs

Asked

Viewed 69 times

1

I’m needing a way to lock a button until the function of the ng-click be completed, to prevent the user from clicking again on the button, thinking that nothing happened or something like.

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

  • Always try to post what you did together so there are no downvotes

  • all right, I’m sorry.

  • +1 the question is good and the explanation dispenses with the placement of codes.

  • 1

    I take back what I said, after seeing your question. You should have put this information in the question before the AR answer.

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;
  );
}
  • So I had thought about this possibility only that since there are many buttons to change, I was trying to find a more practical solution, I don’t know if there is a directive or something that can help me.

  • 1

    @Brayan just applies the same logic by assigning it to an object connected to a button. The answer doesn’t necessarily have to do it for you. He’s shown you the way ;)

  • Got it, I’ll do it this way then, Thanks :D

  • @Brayan if using the ng-repeat, you can do using the object of ng-repeat (I always do like this)

2

As a complement to Otto’s response, 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 ended with failure or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.