How to put a delay on AngularJS instant search?

前端 未结 13 1672
醉梦人生
醉梦人生 2020-11-30 16:55

I have a performance issue that I can\'t seem to address. I have an instant search but it\'s somewhat laggy, since it starts searching on each keyup().

13条回答
  •  一生所求
    2020-11-30 17:29

    Another solution is to add a delay functionality to model update. The simple directive seems to do a trick:

    app.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:

    
    

    So you just use delayed-model in place of ng-model and define desired data-delay.

    Demo: http://plnkr.co/edit/OmB4C3jtUD2Wjq5kzTSU?p=preview

提交回复
热议问题