2014-07-17 118 views
1

我試圖讓搜索輸入框在用戶停止鍵入幾秒後觸發搜索操作。AngularJS:如何在輸入框中輸入後等待幾秒鐘

在一個正常的程序,我這樣做:

$('#search').on('input', _.debounce(function(e) { 
    search(); 
    }, 800)); 

什麼是實現AngularJS類似的事情的正確方法?是否有特定的指令?

示例代碼將不勝感激

+0

你能接受哪個幫你答案? – harishr

回答

1

您可以使用去抖以下指令......

angular.module('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; 

      elm.unbind('input'); 

      var debounce; 
      elm.bind('input', function() { 
       $timeout.cancel(debounce); 
       debounce = $timeout(function() { 
        scope.$apply(function() { 
         ngModelCtrl.$setViewValue(elm.val()); 
        }); 
       }, attr.ngDebounce || 1000); 
      }); 
      elm.bind('blur', function() { 
       scope.$apply(function() { 
        ngModelCtrl.$setViewValue(elm.val()); 
       }); 
      }); 
     } 

    } 
}); 
1

我用這angular-debounce模塊相同

<input type="checkbox" ng-model="blah" debounce="500" immediate="true"></input> 

這爲u如何使用它

編輯

回答你評論...

<input type="checkbox" ng-model="blah" debounce="500" immediate="true" ng-change="search()"></input> 
+0

不幸的是,這不會觸發搜索操作。它只會延遲模型更新。 – finishingmove

+0

因爲你將不得不使用ng-change ...還請避免使用#id時使用#id處理角 – harishr

+0

如果解決了你的問題,請你接受/ upvote答案 – harishr