Call Function with Delay When Textbox Changes in AngularJS

后端 未结 3 883
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 05:08

Can\'t seem to google up an example of how this is done.

I have successfully created a textbox that calls a function every time it changes. What I would like to do is o

3条回答
  •  温柔的废话
    2021-02-01 05:38

    While @charlietfl provided totally acceptable answer I would like to share with you another approach without using $watch method:

    Template:

    
    

    Controller:

        (function (timer, delay) {
            $scope.callDelayed= function () {
                if(timer){
                    $timeout.cancel(timer)
                }
                timer = $timeout(function(){
    
                    /* run code*/
    
                }, delay)
            };
        })(false, 500);
    

    Maybe it's worth to point out why self-executing anonymous function is used. The main reason is to not pollute controller scope with time and delay variables. In this case they are defined in local function scope.

    [UPDATE]

    I've also found an interesting AngularJS project called angular-debounce that makes it really easy to achieve same effect. Using debounce directive it's possible to dealy model update like this:

    
    

提交回复
热议问题