Preventing Repeated Clicks in AngularJS

Looking for a better approach to handle double clicks in AngularJS other than using ng-disabled. I have a solution to disable double/multi-click functionality on button click and re-enable it after completing an ajax process. Any suggestions?

When our code calls the ajax method on button click, it takes a short amount of time to process and retrieve data from the database. We need to prevent multiple clicks during this time.

I want to block any further clicks while the ajax request is in progress...

Please provide simple solutions without relying on ng-disabled, as I am still learning AngularJS.

CreateDialogService('ajs/common/templates/popup/config_reminder_popup.html', { title: isFrom, backdrop: true, controller: 'configRemindersCBController', footerTemplate: '' + action + '' });

$scope.saveOrUpdateReminder = function (reminder)
{
  if ($scope.isDisabled)
  {
    return;
  }
  $scope.isDisabled = true;
  if (!reminder.daysBeforeAfterCheckDate || reminder.daysBeforeAfterCheckDate === '')
  {
    alertService.openValidatPopup('Please enter days before expiration.', "Error", true, 'configRemindersCBController', 'Ok', 'u1_remove.png');
    $scope.isDisabled = false;
    return;
  }

  configRemindersService.isDaysBeforeAfterCheckDate($scope.objectId, reminder, function (result)
  {
    if (!reminder.selectedMessageTemplate.messageId || reminder.selectedMessageTemplate.messageId === '')
    {
      alertService.openValidatPopup('Please select message template.', "Error", true, 'configRemindersCBController', 'Ok', 'u1_remove.png');
      $scope.isDisabled = false;
      return;
    }
    else if (!reminder.selectedReminderSendOption.reminderSendOptionValue || reminder.selectedReminderSendOption.reminderSendOptionValue === '')
    {
      alertService.openValidatPopup('Please select reminder send option.', "Error", true, 'configRemindersCBController', 'Ok', 'u1_remove.png');
      $scope.isDisabled = false;
      return;
    }
    var enableReminder;
    if (result.Result === 'No')
    {
      if (reminder.enable === true)
      {
        enableReminder = 'Enable';
      }
      else
      {
        enableReminder = 'Disable';
      }

      configRemindersService.addOrUpdateReminderConfigLine($scope.objectId, reminder, enableReminder, function (remindersResponse)
      {
        var reminder = remindersResponse.reminderConfigLine;
        $rootScope.CONFIG = JSON.parse(remindersResponse.configData);
        $scope.$modalClose();
        $scope.isDisabled = false;

        _.filter(configRemindersService.getMessageTemplates(), function (msg)
        {
          if (reminder.messageTemplateId === msg.messageId)
          {
            reminder.selectedMessageTemplate = msg;
          }
        });

        _.filter(configRemindersService.getReminderSendOptions(), function (option)
        {
          if (reminder.reminderSendOption === option.reminderSendOptionValue)
          {
            reminder.selectedReminderSendOption = option;
          }
        });

        if (configRemindersService.getIsFrom() === 'Create Reminder')
        {
          configRemindersService.getReminders().push(reminder);
        }
        else
        {
          configRemindersService.getReminders()[configRemindersService.getIndex()] = reminder;
        }
      });
    }
  });
};

Answer №1

Utilizing ng-disabled is the recommended approach for handling object disablement under specific conditions. It serves as a pre-built directive tailored for this purpose.

If the aim is to disable an object without visually indicating its disabled status, there are two potential solutions:

  1. Modify the CSS of the disabled state to give the appearance of being enabled.
  2. Simulate this behavior using a scope variable that triggers actions only when activated.

In the case of the latter option:

$scope.preventClick = false;

$scope.onClick = function () {
    if ($scope.preventClick) { return; }
    $scope.preventClick = true;
    <.. code ..>
    callback: function(data) {
        $scope.preventClick = false;
    }
};

While this method can achieve the desired outcome, it involves duplicating functionality already present and may be less sturdy compared to straightforward element disabling coupled with restyling.

Answer №2

One way to achieve this is as follows:

Start by defining a $scope variable

$scope.myUniquePromise = null;

In the template code:

<button ng-if="myUniquePromise == null"></button>

This will display the button only when myUniquePromise is null.

Next, in your function:

if($scope.myUniquePromise !== null){

  return $scope.myUniquePromise;

}

$scope.myUniquePromise = performTask().finally(function cleanup(){

  //Reset the $scope variable
  $scope.myUniquePromise = null;
})

Answer №3

To manage ongoing http requests and prevent successive click events, one approach is to create a function in the $rootScope that keeps track of the request status. This information can then be used to disable specific buttons.

One common method is to use the fieldset attribute to disable input fields during an active http request.

<fieldset ng-disabled="isWaitingForServerResponse()">  //input fields under this tag will be disabled during ongoing requests       </fieldset>

An example implementation for isWaitingForServerResponse involves utilizing a busy bar feature that displays a loading bar while a http request is in progress. By incrementing a counter for each new request event and decrementing it upon completion, you can effectively track the number of active http requests. Additionally, the $http.pendingRequests property can also be utilized for monitoring pending http requests.

$rootScope.numberOfResponseWaitingFromServer = 0;
$rootScope.$on("cfpLoadingBar:loading", function (event) {
  $rootScope.numberOfResponseWaitingFromServer++;
});
$rootScope.$on("cfpLoadingBar:loaded", function (event) {
  $rootScope.numberOfResponseWaitingFromServer--;
});
$rootScope.isWaitingForServerResponse = function () {
  return $rootScope.numberOfResponseWaitingFromServer > 0;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

Using ng-options with the Add New feature is not compatible with the select statement

Hello everyone, I have some JSON values that look like this: [{"Employee":{"Emp_id":"EF00001","First_name":"Aruna","Last_name":"Jayalath"}}] Unfortunately, I am having trouble retrieving the values within the select statement when running this function i ...

Create animated changes in height for a mdDialog as elements are shown or hidden

Utilizing Angular Material, I have implemented tabs within an md-dialog. The dialog smoothly adjusts its height based on the content of the active tab during navigation. However, when utilizing an ng-if directive to toggle visibility of content, there is n ...

What is the process of utilizing an npm package as a plain JavaScript library through require and module export?

Hey there, I'm a bit unsure if I'm on the right track with my question, but here it goes: What steps do I need to take to modify a node.js package for use as a standalone embedded script/library in HTML? How can I invoke a class constructor in ...

What is the best approach to sending numerous queries from a single endpoint using Express?

I am attempting to perform multiple database queries and create an object that stores each response from the database in a specific field. Below is the code I have written: router.post('/search', (req, res) => { var collection = db.get(). ...

Using Javascript to dynamically add variables to a form submission process

Looking to enhance my javascript skills, I've created a script that locates an existing id and exchanges it with a form. Inside this form, I'm aiming to incorporate javascript variables into the submit url. Unsure if this is feasible or if I&apo ...

Best Practices for Implementing JSON.stringify() with an AJAX Request

While I have a limited understanding of ajax and JSON, I am aware that using JSON.stringify in an ajax call can sometimes be beneficial. The ajax call below is functioning properly, whereas the one following it with the stringify method is not. I am unsure ...

Disabling cookies disables Yii2 CSRF protection

I am encountering an issue with crsf verification in my AJAX requests on Yii2. Crsf is enabled in the config file 'request'=>array( 'enableCsrfValidation'=>true, 'enableCookieValidation'=>true, ) ...

Having issues with the custom listing feature in Jquery UI auto complete not functioning as expected

I am facing an issue with my implementation of jquery UI autocomplete. The autocomplete functionality is not working as expected, despite the absence of any JavaScript errors. Below is the JSON data that I am working with: {"d":"[{\"label\":&bs ...

Participants will utilize functions to predict a number between 1 and 1000

I am currently working on a project that involves creating a number guessing game for the user. The idea is to have the program generate a random number between 1 and 1000, and then prompt the user to guess the number. If the guess is too low or too high ...

Can you merge multiple req.body requests?

I am exploring a scenario where I have a list of items that need to be iterated through, with each item having the value of i added to it to retrieve the next set of information. For example: By concatenating the string "req.body.item" + i + "Title", you ...

Fade out the notification div using jQuery in MVC4

I'm a beginner in the world of JavaScript and JQuery and I could really use some assistance with resolving a simple issue that I've encountered. As part of my application's functionality, I am dynamically loading the following div based on ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...

JavaScript Evaluation Error

try { eval(somejavascript); } catch(e) { console.log(e); } When I encounter runtime errors like: TypeError: Cannot call method 'leftPad' of undefined I wonder if there is any way to debug this error. Specifically, I'm looking for ...

Employing the MVC framework along with AngularJS and the Sortable feature, ensure that the nodes are sorted by

I am facing an issue with the sorting of nodes in a list. Whenever I create multiple nodes in the same session and then update the site, the nodes are randomly sorted. Is there a way to make them sort by the latest created node so that the first created no ...

Automatically executing JavaScript function on an AngularJS webpage

Within my AngularJS webpage, I have implemented a self-invoking function. One crucial aspect of this function is the getData() method, responsible for making Ajax calls to fetch data upon page load and user interactions. <script type="text/javascript"& ...

Encountered a NodeJS error while attempting to locate information in a mongo DB: UnhandledPromiseRejectionWarning

In my MEAN stack application, I am working on implementing a login feature that includes social login functionality. When a new user attempts to log in using Facebook, I need to verify if their Facebook account is already registered in my MongoDB database. ...

When exporting data from Datatable to Excel, decimal values including the % symbol may experience rounding issues

I am facing an issue when trying to export a Datatable to an excel sheet. The column in the Datatable contains decimal values with a % symbol. However, after exporting, the decimal values are being rounded off. I need the decimal values along with the % sy ...

Error: Trying to access properties of an undefined object (specifically 'promise.data.map')

Currently, I am in the process of writing unit tests for a project built with Angular version 1.2. For my controller tests, I have set up a mockService that returns a deferred promise. One of the service methods looks like this: function getItems() { ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...