Skip to content

Instantly share code, notes, and snippets.

@tommaitland
Last active November 9, 2018 02:17
Show Gist options
  • Save tommaitland/7579618 to your computer and use it in GitHub Desktop.
Save tommaitland/7579618 to your computer and use it in GitHub Desktop.
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;
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());
});
});
}
}
});
@jonkri
Copy link

jonkri commented Jul 9, 2015

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

@mlent
Copy link

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