John Fu
John Fu

Reputation: 1832

Debouncing ng-keypress

Does anyone have any pointers for me to debounce the keypress event in angular? I can't get it to debounce. And I know for sure because I'm using $log.debug to print out the keys pressed, and the amount of times it fires off is not at the debounce rate.

I have set it up like this:

<div ng-keypress="doSomething"></div>

and in my controller (not that I have included underscore.js to utilize its debounce method in this instance):

...
$scope.doSomething = function(event, keyEvent) {
    var keypressed = String.fromCharCode(keyEvent.which).toUpperCase();
    _.debounce(handleKeyPress(keypressed), 500);
}

function handleKeyPress(keypressed) {
    //do something with the keypress
}

Thanks for your help in advance.

Upvotes: 0

Views: 3144

Answers (1)

Michael Benford
Michael Benford

Reputation: 14114

Try the following code:

$scope.doSomething = _.debounce(function(event, keyEvent) {
    $scope.$apply(function() {
    // Do something here
    });
}, 500);

Working Plunker

As @Enzey said, _.debounce() returns a "debounced" function that needs to be called somewhere to have any effect. And you need to call $apply() in order to trigger a digest cycle. Otherwise any changes on the model made within the debounced function won't update the view.

Update

It turned out that what the OP really wanted was a throttled function. Below is another code snippet using _.throttle():

$scope.doSomething = _.throttle(function($event) {
    if ($scope.$$phase) return; // Prevents 'digest already in progress' errors

    $scope.$apply(function() {
        // Do something here
    });
}, 100);

Upvotes: 1

Related Questions