How to put a delay on AngularJS instant search?

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

    UPDATE

    Now it's easier than ever (Angular 1.3), just add a debounce option on the model.

    Updated plunker:
    http://plnkr.co/edit/4V13gK

    Documentation on ngModelOptions:
    https://docs.angularjs.org/api/ng/directive/ngModelOptions

    Old method:

    Here's another method with no dependencies beyond angular itself.

    You need set a timeout and compare your current string with the past version, if both are the same then it performs the search.

    $scope.$watch('searchStr', function (tmpStr)
    {
      if (!tmpStr || tmpStr.length == 0)
        return 0;
       $timeout(function() {
    
        // if searchStr is still the same..
        // go ahead and retrieve the data
        if (tmpStr === $scope.searchStr)
        {
          $http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
            // update the textarea
            $scope.responseData = data.res; 
          });
        }
      }, 1000);
    });
    

    and this goes into your view:

    
    
    
    

    The mandatory plunker: http://plnkr.co/dAPmwf

提交回复
热议问题