[英]AngularJS: How do I watch a form for changes, but throttle the rate of JSON requests?
我有一个搜索表单,我想在每次其中一个字段发生变化时自动更新结果。 我想限制对服务器的 JSON 请求的速率。 我该怎么做?
例子
[Name] [Age] [Subjects]
=======================
// Results automatically updated
使用 ng-model-options 延迟调用搜索,像这样
ng-model-options="{debounce: {'default': 1000, 'blur': 0}}"
将此添加到每个文本框
Name: <input type="text" ng-model="student.name"
ng-model-options="{debounce: {'default': 1000, 'blur': 0}}">
Age: <input type="text" ng-model="student.age"
ng-model-options="{debounce: {'default': 1000, 'blur': 0}}">
Subject: <input type="text" ng-model="student.subject"
ng-model-options="{debounce: {'default': 1000, 'blur': 0}}">
直到 1 秒或您离开控件后,它才会更新值。
$scope.$watch('student', function(newval, oldval) {
if(newval != oldval){
//call the search method
}
}, true)
假设您有一个搜索系统,可以让您搜索
<h1>Student Search</h1>
Name: <input type="text" ng-model="student.name">
Age: <input type="text" ng-model="student.age">
Subject: <input type="text" ng-model="student.subject">
控制器代码:
$scope.$watchCollection('student', function() {
$timeout.cancel($scope.delayedRequest);
$scope.delayedRequest = $timeout(function() {
// REST Request in here!
}, 1000);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.