我有一个带角度的实时数据库搜索,我绑定变量$ scope.city,html:
<div class="col-lg-8">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">City@</span>
<input type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">
</div>
</div>
控制器:
app.controller('forecastController', ['$scope','varService','$http', function($scope,varService,$http){
$scope.city = varService.city;
$scope.days = 2;
$scope.$watchGroup(['days', 'city'], function() {
$http.get('http://api.openweathermap.org/data/2.5/forecast?q='+$scope.city+'&mode=json&appid=e652a2c384655ea24f5b12d2fb84c60f&cnt='+$scope.days+'&units=metric')
.then(function(data) { $scope.forecast = data; });
});
}]);
正如你在$ scope.city每次更改时都可以看到$ http.get()数据一样,但它消耗了太多资源,我需要一个解决方案,它会在用户每隔3-4秒调用$ http.get输入一些东西,$ timeout不能完成这项工作,请帮助,谢谢
答案 0 :(得分:1)
您可以使用ng-model-options
指定模型更改时的延迟。然后,您可以使用ng-change
触发功能以获得预测。
<input ng-model-options"{updateOn: 'default blur', debounce: { 'default': 4000, 'blur': 0 }}" ng-change="getForecast(city)" type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">
然后在你的控制器中:
$scope.getForecast = function(city) { $http.blahblahblah; }
答案 1 :(得分:1)
在这种情况下,您需要一些自定义逻辑。 就像在募集事件时,$ watchGroup然后它需要停止执行一秒钟,然后再执行你的过程。
以下示例步骤将为您提供帮助。
<div data-ng-app="app">
<div class="col-lg-8" data-ng-controller="appctrl">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">City</span>
<input type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">
</div>
</div>
</div>
<script>
var app = angular.module('app', []);
app.controller('appctrl', function ($scope, $http, $timeout) {
$scope.city = "";
$scope.days = 2;
var filterTextTimeout;
$scope.$watchGroup(['days', 'city'], function () {
if (filterTextTimeout) $timeout.cancel(filterTextTimeout); // cancel all previous register watchGroup event
filterTextTimeout = $timeout(function () {
alert($scope.city); // in this place call you api for get the response
}, 5000); // delay
});
});
</script>