ang*_*244 26 angularjs angularjs-scope
我在控制器内部有一个基于setInterval的函数.我注意到,在第一次调用它之后,它工作正常,但即使在路线改变后仍然继续.之后我尝试使用本机$ interval服务,它会自动跟踪范围的变化.然而问题仍然存在.所以现在我有两个问题.第一个是我能做什么,以便我在特定控制器内使用重复功能,当用户离开该路线时停止?另外,为什么范围功能会继续,因为我改变了范围?
更新 - 代码是这样的
$scope.refreshScore() {
....
}
$scope.refreshMe = function(){
$interval($scope.refreshScore, 10000);
}
Run Code Online (Sandbox Code Playgroud)
cal*_*oyd 38
也许尝试在范围的destroy事件上取消它.
$scope.refreshScore() {
....
}
var intervalPromise;
$scope.refreshMe = function(){
intervalPromise = $interval($scope.refreshScore, 10000);
}
$scope.$on('$destroy',function(){
if(intervalPromise)
$interval.cancel(promiseFromInterval);
});
Run Code Online (Sandbox Code Playgroud)
$interval可能不是最好的解决方案,特别是如果它是一些异步操作.如果你绝对需要一些定时操作,你希望每隔x ms发生一次,我会使用这样的东西:
var refreshingPromise;
var isRefreshing = false;
$scope.startRefreshing = function(){
if(isRefreshing) return;
isRefreshing = true;
(function refreshEvery(){
//Do refresh
//If async in then in callback do...
refreshingPromise = $timeout(refreshEvery,10000)
}());
}
Run Code Online (Sandbox Code Playgroud)
然后做同样的事情
如果您在取消刷新时遇到问题,可以尝试订阅某种路由更改事件.并在那里做.
Mat*_*att 10
试试这个:
$scope.refreshScore = function() {
// your logic here
}
var promise = $interval($scope.refreshScore, 10000);
$scope.$on('$destroy',function(){
if(promise)
$interval.cancel(promise);
});
Run Code Online (Sandbox Code Playgroud)
更改路线时会破坏间隔.
| 归档时间: |
|
| 查看次数: |
14886 次 |
| 最近记录: |