Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Debounce/Throttling Directive for Angular JS 1.2+
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;
var debounce;
elm.bind('input', function() {
debounce = $timeout( function() {
scope.$apply(function() {
}, attr.ngDebounce || 1000);
elm.bind('blur', function() {
scope.$apply(function() {

tommaitland commented Mar 10, 2014

Props to @lucascsilva for the tip making the delay configurable.

lboynton commented Oct 9, 2014

Thanks for this. Has anyone else seen the debounce not taking effect in IE9?

nbering commented Jan 6, 2015

This feature is available as part of ng-model-options directive in angular 1.3.x, but until some of my project's major dependencies update to 1.3.x, this works perfectly! Thank you! By the way... I'm not sure if there is an implied license on gists, but do we have permission to use this?

jonkri commented Jul 9, 2015

I would appreciate a permissive open source license for this Gist.

mlent commented Aug 11, 2015

FYI, this breaks ng-required, in that you will be able to put a bunch of spaces as input in your text input, and it will not be considered "empty" by ng-required. This is because angular normally trims ngModel itself, but a direct assignment like this, elem.val(), includes spaces and by-passes angular's built-in trimming.

Long story short: You can fix this by replacing elem.val() with elem.val().trim().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment