Skip to content

Instantly share code, notes, and snippets.

@bigs
Last active December 24, 2015 22:59
Show Gist options
  • Save bigs/6877014 to your computer and use it in GitHub Desktop.
Save bigs/6877014 to your computer and use it in GitHub Desktop.
a debounce directive for angular.js
/*
Usage
----------------
HTML
<input type="text"
ng-model="fooVal"
ng-debounce="foo()"
ng-debounce-millis="500">
JavaScript (in the controller)
$scope.foo = function () {
console.log($scope.fooVal);
};
*/
(function () {
var ngDebounce = angular.module('ngDebounce', []);
ngDebounce.directive('ngDebounce', ['$timeout', function ($timeout) {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, elem, attrs, ctrl) {
var changeFnName = attrs.ngDebounce
, millis = attrs.ngDebounceMillis ? scope.$eval(attrs.ngDebounceMillis) : 500;
var t = undefined;
ctrl.$viewChangeListeners.push(function () {
if (t !== undefined) {
$timeout.cancel(t);
}
t = $timeout(function () {
scope.$eval(changeFnName);
t = undefined;
}, millis);
});
}
};
}]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment