Skip to content

Instantly share code, notes, and snippets.

@joshperry
Created August 26, 2014 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshperry/11ce1c2cd4b69ba66de1 to your computer and use it in GitHub Desktop.
Save joshperry/11ce1c2cd4b69ba66de1 to your computer and use it in GitHub Desktop.
'use strict';
angular.module('saidpApp')
.directive('ngDebounce', function ($timeout) {
return {
restrict: 'A',
require: '?ngModel',
priority: 99,
link: function (scope, elm, attr, ngModel) {
if (!ngModel || attr.type === 'radio' || attr.type === 'checkbox') {
return;
}
var delay = parseInt(attr.ngDebounce, 10);
if (isNaN(delay)) {
delay = 500;
}
elm.unbind('input');
var timerId;
elm.bind('input', function () {
$timeout.cancel(timerId);
timerId = $timeout(function () {
scope.$apply(function () {
ngModel.$setViewValue(elm.val());
});
}, delay);
});
// Update value immediately on blur
elm.bind('blur', function () {
if(timerId) {
scope.$apply(function () {
ngModel.$setViewValue(elm.val());
});
}
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment