angularjs - 为 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,但似乎无法让它工作。
解决方案
您可以使用角度超时来实现您想要的结果。
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 秒内没有写任何内容,我们可以提示用户输入。
推荐阅读
- php - 将列创建日期和订单号添加到 WooCommerce 我的帐户订单
- bash - 将 perf 输出通过管道传输到文件中
- elasticsearch - Elasticsearch 中的复合同义词
- linux - 在所有 udev 规则通过并且设备完全初始化后运行脚本
- sql - 从多对多关系获取整个列表
- javascript - 发布路线不返回任何内容
- regex - Regex to catch comma-separated decimal numbers not inside latex command
- css - 在 React 中使用过渡覆盖导航栏
- node.js - 部署后:带有 Office365 和 SSLv3 的节点 IMAP MailListener 错误:140059098205512:error:1408F10B:SSL
- r - 如何根据其他变量中的值为每个人创建二进制变量?