I was wondering whether or not it is possible to implement a slight delay on $scope.$watch. I have the following which queries the server, so I\'d like to implement a slight del
Just a snippet that I found useful for similar case:
function watchWithDelay(scope, prop, callback, delayMs) {
delayMs = delayMs || 1000;
var lastTimeChanged = new Date();
scope.$watch(prop, function(n, o) {
lastTimeChanged = new Date();
setTimeout(function() {
var diff = new Date().getTime() - lastTimeChanged.getTime();
if (diff < delayMs-100 || diff > delayMs+100) {
return;
}
callback(n, o);
}, delayMs);
});
}
You can use it in a controller like this:
watchWithDelay($scope, 'client.phone', function(n, o) {
if (n === o) {
return;
}
// any custom validations, for example
if (!n) {
return alert('Phone is required');
}
if (n.length < 11) {
return alert('Phone is shorter than 11 digits');
}
// here I should save it somehow
console.log('Phone is changed to ' + n);
});