Can I debounce or throttle a watched <input> in AngularJS using _lodash?

前端 未结 4 1177
长发绾君心
长发绾君心 2020-12-08 03:54

I have the following which does a watch on an field that\'s bound to $scope.id. Every time the input field value changes the watch function gets e

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 04:46

    I know the question asks for a lodash solution. Anyway here is an angular only solution:

    app.factory('debounce', function($timeout) {
        return function(callback, interval) {
            var timeout = null;
            return function() {
                $timeout.cancel(timeout);
                var args = arguments;
                timeout = $timeout(function () { 
                    callback.apply(this, args); 
                }, interval);
            };
        }; 
    }); 
    

    In the controller:

    app.controller('BlaCtrl', function(debounce) {
    
        $scope.$watch("id", debounce(function (id) {
            ....
        }, 1000));
    
    });
    

提交回复
热议问题