Search code examples
javascriptangularjsangular-ngmodeldebouncing

Angularjs debounce is clearing my radio input


I have the following radio button group:

<input type="radio" name="GROUP" ng-model="data1" id="for1" value="value" ng-change="formSubmit()" ng-model-options="{debounce: 3000}">
<input type="radio" name="GROUP" ng-model="data2" id="for2" value="value" ng-change="formSubmit()" ng-model-options="{debounce: 3000}">

As you can see, on ng-click, I have it run a particular function but also have a debounce to only occur with a 3 second timeout.

When I have ng-model-options="{debounce: 3000}" present, very often, my radio groups will uncheck- meaning no input's in the group will be checked.

When I remove the debounce, this problem doesn't occur.

Does anyone know how I can fix this?


Solution

  • Based on comment thread above, and assuming you want to keep the first click and ignore subsequent ones within the 3 second delay, I'd suggest:

    <input type="radio" ng-change="doItLater();" value="X">

    (meanwhile, in a directive:

    scope.doItLater = function() {
        if (scope.timeoutwatcher !== undefined) {return;}
        scope.timeoutwatcher = $timeout(function() {
            // do it
            delete scope.timeoutwatcher;
        },3000);
    }
    

    Or if you're looking to let later clicks within the timeout period override earlier ones,

    scope.doItLater = function() {
        $timeout.cancel(scope.timeoutwatcher);
        scope.timeoutwatcher = $timeout(function() {
            // do it
        },3000);
    }