How to put a delay on AngularJS instant search?

前端 未结 13 1602
醉梦人生
醉梦人生 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:53

    I solved this problem with a directive that basicly what it does is to bind the real ng-model on a special attribute which I watch in the directive, then using a debounce service I update my directive attribute, so the user watch on the variable that he bind to debounce-model instead of ng-model.

    .directive('debounceDelay', function ($compile, $debounce) {
    return {
      replace: false,
      scope: {
        debounceModel: '='
      },
      link: function (scope, element, attr) {
        var delay= attr.debounceDelay;
        var applyFunc = function () {
          scope.debounceModel = scope.model;
        }
        scope.model = scope.debounceModel;
        scope.$watch('model', function(){
          $debounce(applyFunc, delay);
        });
        attr.$set('ngModel', 'model');
        element.removeAttr('debounce-delay'); // so the next $compile won't run it again!
    
       $compile(element)(scope);
      }
    };
    });
    

    Usage:

    
    

    And in the controller :

        $scope.search = "";
        $scope.$watch('search', function (newVal, oldVal) {
          if(newVal === oldVal){
            return;
          }else{ //do something meaningful }
    

    Demo in jsfiddle: http://jsfiddle.net/6K7Kd/37/

    the $debounce service can be found here: http://jsfiddle.net/Warspawn/6K7Kd/

    Inspired by eventuallyBind directive http://jsfiddle.net/fctZH/12/

提交回复
热议问题