Angularjs的debounce正在清除我的无线电输入

Angularjs debounce is clearing my radio input

本文关键字:我的 无线电 输入 清除 debounce Angularjs      更新时间:2023-09-26

我有以下单选按钮组:

<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}">

如您所见,在ng-click上,我让它运行一个特定的函数,但也让debounce只在3秒超时时发生。

当我有ng-model-options="{debounce: 3000}"存在时,通常,我的无线电组将取消选中-这意味着组中没有输入将被选中。

当我删除debounce时,这个问题就不会发生了。

有人知道我怎么能解决这个问题吗?

根据上面的评论,假设你想保留第一次点击,并在3秒延迟内忽略后续的点击,我建议:

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

(同时,在指令中:

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

或者,如果您希望在超时时间内让稍后的单击覆盖先前的单击,

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

这样做可能会有帮助

angular
    .module('app', [])
    .controller('example', ['$scope', function($scope) {
        $scope.user = {};
        $scope.$watch('user.gender', $scope.callback);
        $scope.callback = function() {
            alert($scope.user);
        }
    }]);

在HTML中输入

  <form ng-app="app" ng-controller="example">
    <input name="jim" type="radio" ng-model="user.gender" value="male" ng-model-options="{debounce: 3000}" />male
    <input name="jim" type="radio" ng-model="user.gender" value="female" ng-model-options="{debounce: 3000}" />female
    <br />
  <pre>form = {{user | json}}</pre>