简体   繁体   English

AngularJS-一种使HTML输入超时一秒钟然后调用$ watch的方法

[英]AngularJS - a way to timeout html input for a second and then call $watch

For example: I am typing in input text, that has an ng-model, and the $watch gets called instantly. 例如:我输入具有ng模型的输入文本,并且$ watch立即被调用。 Is there a way to call $watch after, let's say 2sec have passed from the last key pressed on the input control? 假设从输入控件上按下的最后一个键起经过了2秒,是否可以调用$ watch?

I wrote a simple directive for this kind of tasks. 我为此类任务编写了一个简单的指令。 Consider this code: 考虑以下代码:

.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);
            });
        }
    };
});

Usage: 用法:

<input type="text" delayed-model="searchText" data-delay="500" />

So the only thing you need to change is you use delayed-model instead of ng-model . 因此,您唯一需要更改的就是使用delayed-model而不是ng-model

Demo: http://plnkr.co/edit/NuKE5Jt1aFY1RJsO71Jw?p=preview 演示: http//plnkr.co/edit/NuKE5Jt1aFY1RJsO71Jw?p = preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM