AngularJS 1.3+
Since AngularJS 1.3 you can utilize the debounce
property ngModelOptions
provides to achieve that very easy without using $timeout
at all. Here's an example:
HTML:
<div ng-app='app' ng-controller='Ctrl'>
<input type='text' placeholder='Type a name..'
ng-model='vm.name'
ng-model-options='{ debounce: 1000 }'
ng-change='vm.greet()'
/>
<p ng-bind='vm.greeting'></p>
</div>
JS:
angular.module('app', [])
.controller('Ctrl', [
'$scope',
'$log',
function($scope, $log){
var vm = $scope.vm = {};
vm.name = '';
vm.greeting = '';
vm.greet = function greet(){
vm.greeting = vm.name ? 'Hey, ' + vm.name + '!' : '';
$log.info(vm.greeting);
};
}
]);
-- OR --
Check the Fiddle
Before AngularJS 1.3
You'll have to use $timeout to add a delay and probably with the use of $timeout.cancel(previoustimeout) you can cancel any previous timeout and run the new one(helps to prevent the filtering to be executed multiple times consecutovely within a time interval)
Here is an example:
app.controller('MainCtrl', function($scope, $timeout) {
var _timeout;
//...
//...
$scope.FilterByName = function() {
if(_timeout) { // if there is already a timeout in process cancel it
$timeout.cancel(_timeout);
}
_timeout = $timeout(function() {
console.log('filtering');
_timeout = null;
}, 500);
}
});
You could use $timeout
to add a delay and probably with the use of $timeout.cancel(previoustimeout)
you can cancel any previous timeout and run the new one(helps to prevent the filtering to be executed multiple times consecutovely within a time interval)
Example:-
app.controller('MainCtrl', function($scope, $timeout) {
var _timeout;
//...
//...
$scope.FilterByName = function () {
if(_timeout){ //if there is already a timeout in process cancel it
$timeout.cancel(_timeout);
}
_timeout = $timeout(function(){
console.log('filtering');
_timeout = null;
},500);
}
});
Plnkr
I know the question is too old. But still want to provide one quicker way to achieve this using debouncing.
So the code can be written as
<input ng-model="xyz" ng-change="FilterByName()" ng-model-options="{debounce: 500}"/>
Debounce will take the number in milliseconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With