Reputation: 24572
I set up a watch expression that watches some data that is entered into an input field that is backed up by the $scope.pid
$scope.$watch("pid", function (pid) {
if (pid == null || pid === "") {
$scope.pidLower = null;
$scope.pidUpper = null;
}
else if (pid.indexOf("-") > 0) {
pid = pid.split("-");
$scope.pidLower = parseInt(pid[0]);
$scope.pidUpper = parseInt(pid[1]);
}
else {
$scope.pidLower = parseInt(pid);
}
});
It works good but once the pidLower or pidUpper change then there are more functions that are called and some heavy processing. The result is that I have to wait a short time in between entering numbers into the input field.
Is there a way I can add some kind of timeout to this so that the watch function code does not change anything until the information entered into the input field has not changed for three seconds?
Upvotes: 0
Views: 110
Reputation: 6066
You can use the $timeout service for this. After you've injected this service into your controller you can do the following:
var parsePid = function() {...};
$scope.$watch("pid", function (pid) {
if($scope.timeoutPromise) {
$timeout.cancel($scope.timeoutPromise);
}
$scope.timeoutPromise = $timeout(function() {
parsePid();
}, 3000);
});
Upvotes: 1
Reputation: 274
I think you want to validate your input before further processing. Instead of watching pid
you can add filter. In filter you can change $scope.pidLower
and $scope.pidUpper
based on some condition , which will trigger your further heavy processing. Refer $filter for details.
Upvotes: 0