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()); | |
}); | |
}); | |
} | |
} | |
}); |
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()
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?