jeffci
jeffci

Reputation: 2622

Call function on ultra fast keyup and keydown events with AngularJS

I have this function in my controller that triggers a search function in my controller to do a search.

$scope.fetchScannedData = function () {
    $timeout.cancel(fetchScannedDataTimer);
    fetchScannedDataTimer = $timeout(function () {
        $scope.search(); // do search with 5 second delay
    }, fetchScannedDataDelay);
};

Here is my input field:

 <input type="text" class="form-control" ng-enter="search()" placeholder="Enter Search ID" ng-change="fetchScannedData()" ng-model="id">

(note the ng-change directive on my form field that triggers a 5 second delay)

My question is how do I edit this delayScannedData function so that the delay is ONLY triggered if the text entered is uultra fast by a non-human (barcode scan) but have no delay when the text entered is done by a human typing?

Upvotes: 0

Views: 1073

Answers (1)

Shaun Bohannon
Shaun Bohannon

Reputation: 491

I would suggest wrapping your call in a debounce:

https://lodash.com/docs#debounce

Or even easier if you change your code structure you could use the Angular 1.3 ngModelOptions:

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

By change the structure I mean that instead of what you have you would have:

$scope.searchParams = {};

$scope.$watch('searchParams.query', function(newVal, oldVal){
   if(newVal !== oldVal){
      $scope.fetchScannedData();
   }
});

$scope.fetchScannedData = function () {
    $timeout.cancel(fetchScannedDataTimer);
    fetchScannedDataTimer = $timeout(function () {
        $scope.search(); // do search with 5 second delay
    }, fetchScannedDataDelay);
};

 <input type="text" class="form-control" ng-enter="search()" placeholder="Enter Search ID" ng-model="searchParams.query" ng-model-options="{ debounce: 1000 }">

Not sure what your search() method looks like that but you would need to make sure you changed it to point to the searchParams.query string.

I think this approach would be more 'Angular' than the one you are currently taking.

Upvotes: 1

Related Questions