开始新的控制器时,停止$超时 [英] Stop $timeout when starting new controller
问题描述
我为每2秒我的数据,让他们更新页面上投票。我的问题是,当我访问另一页的超时保持活动状态。我怎样才能取消我超时,当我访问一个新的页面?
函数IndexCtrl($范围,$超时,RestData){
$ scope.rd = {}; (函数getRestDataFromServer(){
RestData.query(功能(数据){
$ scope.rd =数据;
$超时(getRestDataFromServer,2000年);
});
})();
}
//编辑
我找到了解决办法,但我不知道这是否是一个好。当我将超时保存到$ rootScope,我可以取消所有其它控制器。
函数IndexCtrl($范围,$ rootScope,$超时,RestData){
$ scope.rd = {}; (函数getRestDataFromServer(){
RestData.query(功能(数据){
$ scope.rd =数据;
$ rootScope.prom = $超时(getRestDataFromServer,2000年);
});
})();
}功能newPageCtrl($范围,$ rootScope,$超时){
$ timeout.cancel($ rootScope.prom);
}
有几个途径时,正在改变,正在播出角事件。您可以在 IndexCtrl
使用 $范围内听取他们对$
并采取相应的行动:
$破坏事件
VAR承诺= $超时(getRestDataFromServer,2000年);
...$范围。在$('$破坏',函数(){
$ timeout.cancel(承诺);
});
$ locationChangeStart
VAR承诺= $超时(getRestDataFromServer,2000年);
...$范围。在$('$ locationChangeStart',函数(){
$ timeout.cancel(承诺);
});
$超时()
返回一个承诺对象。这个对象可以提供给 $ timeout.cancel()
函数取消超时。
I'm polling for my data every 2 seconds to keep them updated on the page. My problem is when I visit another page the timeout stays active. How can i cancel my timeout when I visit an new page?
function IndexCtrl($scope, $timeout, RestData) {
$scope.rd = {};
(function getRestDataFromServer() {
RestData.query(function(data){
$scope.rd = data;
$timeout(getRestDataFromServer, 2000);
});
})();
}
//EDIT I found a solution, but I'm not sure if it's a good one. When i save my timeout to the $rootScope, I can cancel it in all the other controllers.
function IndexCtrl($scope, $rootScope, $timeout, RestData) {
$scope.rd = {};
(function getRestDataFromServer() {
RestData.query(function(data){
$scope.rd = data;
$rootScope.prom = $timeout(getRestDataFromServer, 2000);
});
})();
}
function newPageCtrl($scope, $rootScope, $timeout) {
$timeout.cancel($rootScope.prom);
}
There are couple of Angular events that are being broadcasted when route is being changed. You can listen for them within the IndexCtrl
using $scope.$on
and act accordingly:
$destroy event
var promise = $timeout(getRestDataFromServer, 2000);
...
$scope.$on('$destroy', function(){
$timeout.cancel(promise);
});
$locationChangeStart
var promise = $timeout(getRestDataFromServer, 2000);
...
$scope.$on('$locationChangeStart', function(){
$timeout.cancel(promise);
});
$timeout()
returns a promise object. This object can be supplied to $timeout.cancel()
function to cancel the timeout.
这篇关于开始新的控制器时,停止$超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!