nickponline
nickponline

Reputation: 25914

How do I prevent multiple clicks on a link in AngularJS?

I have a link that increases a value in the database provided it is below some threshold, something like this:

if (currentValue + 10 < maxValue)
{
$http({method: 'GET', url: 'api.increaseValue/10'}) ...
}

However if I click rapidly the if condition passes for all the clicks and launches a bunch of request concurrently that can take the value over the threshold. Is there a way to handle this elegantly?

Upvotes: 0

Views: 1004

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364707

There are a number of ways to handle this issue. Besides what @praneetloke already mentioned, here are a few more ideas.

  • The click handler/function can first disable the button, send the http request, then enable the button again when you receive confirmation from the server - at which point I assume currentValue would also be updated.
  • Update currentValue locally, keep track of outstanding server requests, then in your http callback, handle any error conditions. E.g., if it did not update on the server side, pop up an error dialog and decrease currentValue appropriately -- i.e., by the number of outstanding server requests.

Upvotes: 3

praneetloke
praneetloke

Reputation: 1971

Use setTimeout() to delay the execution of the function. Also, use a global flag in the function that will return the function execution if that function is currently being executed for a previous click. Then, when your API call returns, reset the flag to allow subsequent clicks to call the function.

This suggestion also depends on what the value being incremented represents. You must decide if your users will be ok with ignoring fast-clicks. If they are intentionally doing it and you do not want to allow it, perhaps you must show a friendly message saying that a previous request is being processed and that they would have to wait before clicking again.

I could possibly improve the answer if you provide some context of this action and show more code of what else this function is doing.

Upvotes: 0

Related Questions