-
-
Save tommaitland/7579618 to your computer and use it in GitHub Desktop.
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()); | |
}); | |
}); | |
} | |
} | |
}); |
Thanks for this. Has anyone else seen the debounce not taking effect in IE9?
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?
I would appreciate a permissive open source license for this Gist.
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()
.
Props to @lucascsilva for the tip making the delay configurable.