首页 > 解决方案 > 为 AngularJS $watch 函数设置超时

问题描述

有没有办法向 AngularJS $watch 函数添加超时?

例如,假设我有下面的 AngularJS 代码正在监视一个值myName。当值改变时,监听函数运行。但是如果值在一段时间内没有变化,我希望它做别的事情。

具体来说,在下面的代码中,我希望 $scope.nothingEnteredFlag 从 false 更改为 true。设置我的 html 模板以反映该标志的状态(例如,使用 ng-show)。

var app = angular.module("helloApp", []);
app.controller("helloCtrl", function($scope) {
    $scope.nothingEnteredFlag=false;
    $scope.$watch("myName", function (newValue, oldValue) {
        if ($scope.myName.length < 5) {
            $scope.message = "Short name!";
        } else {
            $scope.message = "Long name!";
        }
    });
});

小提琴

我试过用 $timeout 包围 $watch,但似乎无法让它工作。

标签: angularjs

解决方案


您可以使用角度超时来实现您想要的结果。

var timer;
  var timerFunction = function() {
    timer = $timeout(function() {
      $scope.nothingEnteredFlag = true;
    }, 5000);
  };

这将创建计时器功能

你的控制器应该像这样

var app = angular.module("helloApp", []);
app.controller("helloCtrl", function($scope, $timeout) {
  $scope.nothingEnteredFlag = false;
  $scope.myName = "";
  $scope.$watch("myName", function(newValue, oldValue) {
    if ($scope.myName.length < 5) {
      $scope.message = "Short name!";
    } else {
      $scope.message = "Long name!";
    }
    $scope.nothingEnteredFlag = false;
    $timeout.cancel(timer);
    timerFunction();
  });
  var timer;
  var timerFunction = function() {
    timer = $timeout(function() {
      $scope.nothingEnteredFlag = true;
    }, 5000);
  };
  timerFunction();
});

如您所见,一旦用户输入任何文本,我们就启用了 5 秒的超时,我们取消计时器并再次启用它,这样如果用户在 5 秒内没有写任何内容,我们可以提示用户输入。

演示


推荐阅读