MGot90 MGot90 - 1 year ago 573
AngularJS Question

Angular ng-change delay

I have an input which filters a ng-repeat list on change. The repeat contains a lot of data and takes a few seconds to filter through everything. I would like their to be 0.5 second delay before I start the filtering process. What is the correct way in angular to create this delay?


<input ng-model="xyz" ng-change="FilterByName()" />


<div ng-repeat"foo in bar">

Filter Function

$scope.FilterByName = function () {
//Filtering Stuff Here


Answer Source

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:


<div ng-app='app' ng-controller='Ctrl'>
    <input type='text' placeholder='Type a name..'
        ng-model-options='{ debounce: 1000 }'

    <p ng-bind='vm.greeting'></p>


angular.module('app', [])
.controller('Ctrl', [
    function($scope, $log){
        var vm = $scope.vm = {}; = '';
        vm.greeting = '';
        vm.greet = function greet(){
            vm.greeting = ? 'Hey, ' + + '!' : '';

-- 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 = $timeout(function() {
            _timeout = null;
        }, 500);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download