Reputation: 63415
I'm trying to have a search input box fire the search operation a few seconds after the user stopped typing.
In a normal app I do like this:
$('#search').on('input', _.debounce(function(e) {
search();
}, 800));
What would be the correct way to achieve something similar in AngularJS? Is there a specific directive?
Sample code would be much appreciated
Upvotes: 2
Views: 2466
Reputation:
you can debounce using below directive...
angular.module('app', []).directive('ngDebounce', function($timeout) {
return {
restrict: 'A',
require: 'ngModel',
priority: 99,
link: function(scope, elm, attr, ngModelCtrl) {
if (attr.type === 'radio' || attr.type === 'checkbox') return;
elm.unbind('input');
var debounce;
elm.bind('input', function() {
$timeout.cancel(debounce);
debounce = $timeout( function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(elm.val());
});
}, attr.ngDebounce || 1000);
});
elm.bind('blur', function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(elm.val());
});
});
}
}
});
Upvotes: 1
Reputation: 18055
i am using this angular-debounce module for the same
<input type="checkbox" ng-model="blah" debounce="500" immediate="true"></input>
this is how u use it
EDIT
to answer your comment...
<input type="checkbox" ng-model="blah" debounce="500" immediate="true" ng-change="search()"></input>
Upvotes: 1