1

keyup in build directive of angular for filtering the record but I want to delay the function call so user can enter the full word and call can go to DB and fetch the record instead of single word. my line of code is

  <input ng-show="!$scope.noRPData" type="text" ng-keyup="filterRP($event)" class="filterRP form-control" id="txtFilterID" ng-model="rpFilter.ModifiedDate.value" />

filterRP is the function for which I want to delay the call by 4 second. Please suggest

1
  • why don't you think of adding timeout in you filterRP() Commented Apr 5, 2018 at 8:35

2 Answers 2

4

I would recommend using ng-change instead of ng-keyup. You can than add the ng-model-options and configure the debounce time there. Then, your model will get changed only after this debounce time period has passed. See the Debouncing updates docs section.

UPDATE: Both ng-change and $scope.$watch should work with ng-model-options debounce option (in AngularJS v1.6.10). See this Plunker

Sign up to request clarification or add additional context in comments.

2 Comments

added this line after your suggestion <input ng-show="!$scope.noRPData" type="text" ng-change="filterRP($event)" ng-model-options="{ debounce: 4000 }" class="filterRP form-control" id="txtFilterRPDescription" ng-model="rpFilter.Description.value" /> its not working
Try using $scope.$watch instead of ng-change like this: $scope.$watch('user.name', function() { ... });, see this Plunker
0

You would need to delay it with $timeout (with additional if statement, to prevent calling every time a key is pressed). Then send some data within that timeout with $http.post request. Here is a simple demo that you can adopt for your example:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout, $http) {
  var typing = false;
  $scope.filterRP = function(e) {
    if (!typing) {
      typing = true;
      $timeout(function() {
        typing = false;
        console.log("sending", $scope.x);
        /*
        var data = {"input":$scope.x}
        $http.post(url,data).
        then(function(response){
        	// do something with response.data;
        },function(error){
        	// log error
        });
        */
      }, 4000) // 4 second delay
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-keyup="filterRP($event)" ng-model="x" />
</div>

2 Comments

This is basically re-implementing the built-in debounce functionality.
@Thomas it's a more controlled version; if statements can be added for the additional logic, timeout can return a promise, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.