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

前端 未结 4 1168
长发绾君心
长发绾君心 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条回答
  •  离开以前
    2020-12-08 04:21

    You can encapsulate this in a directive. Source: https://gist.github.com/tommaitland/7579618

    
    

    Javascript

    app.directive('ngDebounce', function ($timeout) {
      return {
          restrict: 'A',
          require: 'ngModel',
          priority: 99,
          link: function (scope, elm, attr, ngModelCtrl) {
              if (attr.type === 'radio' || attr.type === 'checkbox') {
                  return;
              }
    
              var delay = parseInt(attr.ngDebounce, 10);
              if (isNaN(delay)) {
                  delay = 1000;
              }
    
              elm.unbind('input');
    
              var debounce;
              elm.bind('input', function () {
                  $timeout.cancel(debounce);
                  debounce = $timeout(function () {
                      scope.$apply(function () {
                          ngModelCtrl.$setViewValue(elm.val());
                      });
                  }, delay);
              });
              elm.bind('blur', function () {
                  scope.$apply(function () {
                      ngModelCtrl.$setViewValue(elm.val());
                  });
              });
          }
      };
    });
    

提交回复
热议问题