[英]Call Function with Delay When Textbox Changes in AngularJS
似乎无法谷歌举例说明如何做到这一点。
我已经成功创建了一个文本框,每次更改时都会调用一个函数。 我想要做的只是在用户停止输入x毫秒时调用该函数。
我知道如何使用keyup事件在JQuery中执行它,并且可能使它以这种方式工作,但是想要“Angular Way”。
编辑
也许从标签或文本中不清楚,但我使用的是AngularJS,并希望使用正确的方法来创建这种延迟功能。
这种方式有ng-model-options
<input id="delayedModel" ng-model="delayedModel" ng-change="callDelayed()" ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }" />
callDelayed
方法仅在键入最后一个char或模糊后500毫秒后调用
这是文档https://docs.angularjs.org/api/ng/directive/ngModelOptions
对于angular方法,可以在控制器中注入$timeout
作为依赖项,并在ng-model
指定的范围变量上使用$watch
。
var timer=false;
$scope.ModelName='foo';
$scope.$watch('ModelName', function(){
if(timer){
$timeout.cancel(timer)
}
timer= $timeout(function(){
/* run code*/
},delay)
});
虽然@charlietfl提供了完全可以接受的答案,但我想与您分享另一种不使用$watch
方法的方法:
模板:
<input id="delayedModel" ng-model="delayedModel" ng-change="callDelayed()"/>
控制器:
(function (timer, delay) {
$scope.callDelayed= function () {
if(timer){
$timeout.cancel(timer)
}
timer = $timeout(function(){
/* run code*/
}, delay)
};
})(false, 500);
也许值得指出为什么使用自执行匿名函数。 主要原因是不会使用time
和delay
变量污染控制器范围。 在这种情况下,它们在本地函数范围中定义。
[UPDATE]
我还发现了一个名为angular- debounce的有趣的AngularJS项目,它可以很容易地实现相同的效果。 使用debounce
指令可以对这样的更新进行dealy建模:
<input type="text" ng-model="delayedModel" debounce="500"></input>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.