Angular debounce on checkboxes allows you to prevent multiple rapid changes from

Managing multiple checkboxes to filter a dataset can be tricky. I am looking for a way to debounce the checkbox selection so that the filter is only triggered after a certain period of time, like waiting 500ms to a second after the last checkbox has been clicked.

To see an example, check out my plnkr


       <input type="checkbox"
           ng-model="user.cool"
           ng-model-options="{ debounce: 1000 }"/>
     <input type="checkbox"
           ng-model="user.lame"
           ng-model-options="{ debounce: 1000 }"/>

The current setup queues the click options and changes the model one by one with a delay, but I want both checkboxes to change at the same time. How can I achieve this?

Thank you!

Answer №1

Utilize $scope.$watch within your application controller to manage the outcome of changes in multiple model properties. With $watch, you can assess not just a single property but also an expression; subsequently, the callback can be debounced before notifying Angular about the necessary changes by invoking $scope.$apply.

$scope.$watch('user.lame + user.cool', _.debounce(function (id) {
   $scope.$apply(function() {
      //code that updates UI
   })
}, 1000));

For more information, refer to this article: Can I debounce or throttle a watched <input> in AngularJS using _lodash?

You can view the updated plunk here: https://plnkr.co/edit/AkhEjEg8JCyM32j21MRQ?p=preview

Answer №2

If you use angular's $watchCollection method, you won't need any additional features. It simplifies the process.

(function(angular) {
  'use strict';
  angular.module('optionsExample', [])
    .controller('ExampleController', ['$scope',
      function($scope) {
        $scope.user = {
          name: 'Sara'
        };
        $scope.$watchCollection('user', function(newVal, oldVal) {

          console.log(newVal);
        });
      }
    ]);
})(window.angular);

To make your form more concise, define debounce once and adjust your form like this:

<form name="userForm" ng-model="user" ng-model-options="{ debounce: 1000 }">
  <label>Name:
    <input type="text" name="userName" ng-model="user.name" />
    <input type="checkbox" ng-model="user.cool" />
    <input type="checkbox" ng-model="user.lame" />
  </label>
  <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  <br />
</form>

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

Tips for extracting data from a JQuery table with Python

My goal is to extract information from the top ten items on a manga website using Python Selenium/BeautifulSoup. However, I am facing challenges due to the website loading its content through a jquery script. The tutorials and guides I have followed do not ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Having trouble receiving a complete response when making an ajax request to fetch an entire webpage

Currently, I am experimenting with J-Query Ajax functionality. My goal is to send a request in order to retrieve the entire HTML data of a page that I have hosted on bitbaysolutions.com. The issue arises when I load this URL and execute document.getElement ...

Using Angular Material to alter the value of ng-model in the user interface

here is my perspective <section class="custom-design" layout-padding> <div layout="row"> <md-input-container flex="33"> <label>First Name</label> <input ng-model="firstna ...

What is the manual way to activate Ratchet's push feature?

I am facing an issue with a link that triggers a search function. Currently, the link is working as expected. However, I am having trouble getting the search to be executed by pressing the 'enter' button. Here is my code snippet: $('#sea ...

Tips on sending a function's return value to an object in Node.js

I'm currently exploring Node.js and working on a REST API for a project. One of the functionalities I am implementing is a post request to store form data in a database. Some values will be retrieved from the form data while others will be generated ...

In AngularJS, when a user clicks on a specific element, the program should fetch the corresponding value from a separate dataset and display it

Hello, I am just starting out with angularjs and here is my current js file setup: angular.module("mainModule", []) .controller("mainController", function ($scope) { $scope.ProdMenu = [ {ProductMenuName: "CBS" ...

Adding content to a text field and then moving to the next line

I am looking to add a string to a text area, followed by a new line. After conducting some research, here are the methods I have attempted so far but without success: function appendString(str){ document.getElementById('output').value += st ...

Executing the onSuccess callback in Ajax without any ability to manipulate the ajax requests

My dilemma lies in needing to execute a JavaScript function upon the successful completion of an AJAX call. Unfortunately, I am unable to directly manage the AJAX calls as they are handled by the DNN5 framework. Is there a way for me to trigger my functio ...

Obtaining the final field with the $in operator in Mongoose

I need to retrieve all person records that fall within a time frame specified by start and end dates, and have a place ID of either 1 or 2. Below is the query I am using: Person.find({ time: { $gte: start, $lt: end ...

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

Should the secret for express-session be a fixed value or should it change dynamically?

I'm uncertain whether the secret for this application should remain static or if it can be dynamic. Currently, I am setting the secret as follows: var salt1 = bcrypt.genSaltSync(); var salt2 = bcrypt.genSaltSync(); var secret = bcrypt.hashSync(salt1 ...

Alas, an error has occurred with eslint npm. The elusive 404 Not Found reared its head once more when attempting to access the es

I'm currently in the process of organizing my JavaScript code and preparing to transition to TypeScript. I recently set up node.js, npm, and eslint on my Ubuntu 20.04 system. After doing so, I executed npm -init and eslint -init. $ npx eslist util.js ...

Tips for retrieving nested data objects from a JSON API on the web

Below is the provided API link - I attempted to utilize this jQuery script in order to collect data for each state individually for my project. However, I am facing difficulties accessing the information with the code provided below. $.getJSON('http ...

Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an intercept ...

Storing data locally in Angular applications within the client-side environment

As I delve into Angular and TypeScript, I've encountered a perplexing issue. Let's say I have two classes - Employee and Department. On the server-side, I've established a Many-To-One relationship between these entities using Sequelize: db. ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

The functionality of socket.io is not functioning properly on the server, resulting in a 404

I encountered errors while working on a simple socket.io project on my server. The IP address I am using is . All files are stored in public_html and can be accessed through the URL: . Here are the code snippets: <!doctype html> <html> < ...

Managing the file order within subdirectories for Rails assets

Utilizing rails to power a primarily single page application, I am incorporating angular as well. Within my assets/javascripts directory, I have organized folders for controllers, directives, filters, routes, services, and more. Certain elements, such as ...

Pattern matching for a string with numerous repetitions using Regular Expressions

There's a [tree] and a cat and a [dog] and a [car] too. I am looking to find the words inside each set of square brackets. The resulting array will be tree, dog, car My attempt at using match(/\[(.*)\]/g) didn't work as expected. It ...