您应该使用 debounce 方法 - 当您输入过于频繁时,服务器不应受到影响。当您停止输入并发生超时时,应将请求发送到服务器。您可以使用Underscore Debounce feature 或在此处进行自定义实现:
$scope.loadData = function () {
var loadThrottle;
clearTimeout(loadThrottle);
loadThrottle = setTimeout(function () {
$scope.$apply(function () {
$scope.getData();
});
}, 500);
};
这里的请求只有在你停止输入并且之后发生 500ms 超时时才会发送。
另一种实现方式(使用角度化方法):
$scope.loadData = function(timeout) {
$scope.counter += 1;
var counter = $scope.counter;
$timeout(function(){
if (counter === $scope.counter) {
$scope.getData();
$scope.counter = 0;
}
}, timeout ? timeout : 500);
}
另外一种选择是使用更通用的方法和自定义指令和下划线类似的东西:
app.directive('changeTimeout', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
angular.forEach(ctrl.$viewChangeListeners, function(listener, index) {
ctrl.$viewChangeListeners[index] = _.debounce(function() {
scope.$apply(attrs.ngChange);
}, attrs.changeTimeout || 0)
});
}
}
});