Last active
November 9, 2018 02:17
-
-
Save tommaitland/7579618 to your computer and use it in GitHub Desktop.
Debounce/Throttling Directive for Angular JS 1.2+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
}); | |
}); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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" byng-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()
withelem.val().trim()
.