AngularJS 1.3 +
Since AngularJS 1.3 you can use the debounce property of ngModelOptions , you can achieve this very easily without using $timeout at all. Here is 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 script
Before AngularJS 1.3
You need to use $ timeout to add a delay, and perhaps using $ timeout.cancel (previoustimeout), you can undo any previous timeout and start a new one (helps prevent multiple filtering from happening repeatedly over a period of time)
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); } });
rckd Jan 15 '15 at 8:43 2015-01-15 08:43
source share