如果有时无法对数字输入进行更改,则需要自动触发数字更改功能

时间:2015-10-27 12:46:22

标签: javascript angularjs

我正在使用angularjs(输入[数字])[https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D]。在这种情况下,我需要在几秒钟后自动触发动作,只要在这几秒钟内没有更多的数字更改,比如2秒。

在我的plunker example中,每次数字更改时都会调用该操作,但我只需要在用户未更改任何值超过2秒时触发操作。

<div class="col-md-3 divGridText">
    <label for="excludeMinutesStep" style="font-weight:bold">Exclude tasks &lt; </label>
    <input id="excludeMinutesStep" min="0" max="10" ng-model="excludeValue" ng-change="numericStepperChanged(excludeValue)" size="2" style="width:40px;" type="number" /> <b>minutes</b>
</div>

$scope.excludeValue = 5;
$scope.numericStepperInitValue = 0;

$scope.numericStepperChanged = function(data) {console.log("A");
  $scope.numericStepperHit = true;
  if (data != undefined) {
    $scope.excludeValue = data;
    if (data == 0) {
      $scope.isExcludeNeeded = false;
    }

    if ($scope.numericStepperInitValue == 0) {
      $timeout($scope.callAtNumercStepperChangeTimeout, 2000);
    }
  }
}

$scope.callAtNumercStepperChangeTimeout = function() {
  $scope.numericStepperHit = false;
  $scope.numericStepperInitValue++;
  $scope.changeGraph();
}

$scope.changeGraph = function() {
  if (!$scope.numericStepperHit) {
    console.log("Action called "+$scope.excludeValue);
    $scope.mytext = "Action called "+$scope.excludeValue;
    $scope.isExcludeNeeded = true;
  }
}

2 个答案:

答案 0 :(得分:1)

你需要的是所谓的去抖动,它是一种非常着名的模式。

你可以使用undercoreJs debounce:

$scope.debouncedFunction = _.debounce(myFunction, 2000);

<input ng-change="debouncedFunction()" size="2" style="width:40px;" type="number" />

或者您可以自己实施。像这样:

var promise = null;
function debouncedFcn{
    if(promise)
        $timeout.cancel(promise);
    var promise = $timeout(myFunction, 2000);
}

参考:Debounce

答案 1 :(得分:0)

我创建了一个名为timer的函数,用于检查值是否在2秒内发生了变化。如果没有触发激发警报的mainFunction()。并在$ scope中使用计时器功能。$ watch,表示excludeValue更改

$scope.excludeValue = 5;

 $scope.$watch('excludeValue',function(oldVal,newVal){
   if(oldVal !== newVal) // a new change 
   {
      timer(oldVal,newVal)
   }
 });

 var timer = function(oldVal,newVal){
   var currentVal = angular.copy($scope.excludeValue);
   $timeout(function(){
     if(currentVal == $scope.excludeValue)
     {
       // there is no change made in 2 sec 
       mainFunction()
     }
     else
     {
       // change made in 2 sec
     }
   }, 2000);
 };

 timer();

 var mainFunction = function(){
   alert('No change made in 2 sec.');
 };

这是我的plunker