我试图让搜索输入框在用户停止输入几秒钟后触发搜索操作。
在一个普通的应用程序中,我这样做:
$('#search').on('input', _.debounce(function(e) {
search();
}, 800));
在 AngularJS 中实现类似功能的正确方法是什么?有具体的指令吗?
示例代码将不胜感激
我试图让搜索输入框在用户停止输入几秒钟后触发搜索操作。
在一个普通的应用程序中,我这样做:
$('#search').on('input', _.debounce(function(e) {
search();
}, 800));
在 AngularJS 中实现类似功能的正确方法是什么?有具体的指令吗?
示例代码将不胜感激
您可以使用以下指令去抖动...
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());
});
});
}
}
});
我正在使用这个angular-debounce模块
<input type="checkbox" ng-model="blah" debounce="500" immediate="true"></input>
这就是你使用它的方式
编辑
回答你的评论...
<input type="checkbox" ng-model="blah" debounce="500" immediate="true" ng-change="search()"></input>