希望我能解释一下,以便您理解。我刚刚完成了一个问题,获得有关 angular 的 $interval
功能的帮助。让我们先从基础开始:
- 我有一个下拉菜单,用户可以在其中选择一个选项。
- 该操作调用一个 select 方法,该方法生成一个
$http.get( )
请求。 - 然后使用
mg-repeat
将生成的数据放入列表中。 - 数据可以从另一个服务更新,所以我需要这个列表
定时轮询刷新列表,输入
$interval
在下面的这段代码中,我很接近,但还不够。假设我想每 10 秒刷新一次列表,如果我从一开始就选择选项 1,它将每 10 秒刷新一次选项 1 的列表。很好吧?
现在,如果我选择选项 2,根据我的理解,它似乎会创建另一个线程。它更改了从选项 1 到选项 2 的 $http.get( )
,但它保持选项 1 的 $interval
线程打开。因此它在 10 秒内两次 ping 选项 2 的 $http.get()
。一次遵循第一个请求的时间间隔(对于选项 1),一次在我选择选项 2 的时间间隔内。
这里是选择函数的JS代码。当用户从下拉列表中选择某些内容时会发生这种情况:
$scope.select = function() {
$scope.searchText = '';
$scope.selectedItem = null;
var url = 'http:xxxxxxxxxxxx.com';
url += $scope.selectModel.name;
console.debug("GOING TO: " + url);
$http.get(url).success(function(data2) {
$scope.records = [];
data2.forEach(function(r) {
$scope.records.push(r);
});
});
$interval(function() {
$http.get(url).success(function(data2) {
$scope.records = [];
data2.forEach(function(r) {
$scope.records.push(r);
});
});
}, 30000);
};
这里是有问题的 html 部分:
<div style="margin: 1em">
<h4>Search</h4>
<div role="form">
<!-- start dropdown -->
<div class="form-group">
<select class="form-control" ng-options="model as model.name for model in allModels" ng-model="selectModel" ng-change="select()">
<option value="">Choose Model</option>
</select>
</div>
<!-- /end dropdown-->
<div class="form-group">
<input id="start_date" type="text" class="form-control" placeholder="Threat Date">
</div>
</div>
<div>
<table class="table table-hover table-striped" ng-show="records">
<thead>
<th>#</th>
<th>Name</th>
<th>Score</th>
</thead>
<tr data-ng-repeat=" item in records | orderBy : '-score' | limitTo : 10 " ng-click="moreInfo(item)">
<td>{{$index+1}}</td>
<td>{{item.name.slice(5)}}</td>
<td>{{item.score.toFixed(3)}}</td>
</tr>
</table>
</div>
</div>
如果我需要澄清一些,请告诉我。谢谢。
最佳答案
您需要取消间歇。
// Activate
var myInterval = $interval(....);
// Deactivate
$interval.cancel(myInterval);
myInterval = undefined; // Necessary for conditional checking
关于javascript - $interval 发生太多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29929841/