[英]AngularJS - a way to timeout html input for a second and then call $watch
例如:我输入具有ng模型的输入文本,并且$ watch立即被调用。 假设从输入控件上按下的最后一个键起经过了2秒,是否可以调用$ watch?
我为此类任务编写了一个简单的指令。 考虑以下代码:
.directive('delayedModel', function() {
return {
scope: {
model: '=delayedModel'
},
link: function(scope, element, attrs) {
element.val(scope.model);
scope.$watch('model', function(newVal, oldVal) {
if (newVal !== oldVal) {
element.val(scope.model);
}
});
var timeout;
element.on('keyup paste search', function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
scope.model = element[0].value;
element.val(scope.model);
scope.$apply();
}, attrs.delay || 500);
});
}
};
});
用法:
<input type="text" delayed-model="searchText" data-delay="500" />
因此,您唯一需要更改的就是使用delayed-model
而不是ng-model
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.