执行取消$timeout的简单任务不起作用。我有一个状态框,其中包含给用户的消息,所以如果在超时运行之前设置了一个新消息,那么我需要通过取消它并重新启动它来重新启动超时。
我看过这个网站上的文档和其他答案,但我似乎并没有做什么不同的事情。
我没有错误。我做错了什么?
服务:
core.service('statusHandler', ['$timeout', function($timeout) {
var status = {
message: '',
isSuccess: false,
isActive: false,
isBoxDirective: false,
timeout: null
};
this.resetStatus = function() {
status.isSuccess = false;
status.isActive = false;
status.isBoxDirective = false;
$timeout.cancel(status.timeout);
};
this.setStatus = function(message, isSuccess, isBoxDirective) {
status.message = message || 'Something went wrong';
status.isSuccess = isSuccess;
status.isActive = true;
status.isBoxDirective = isBoxDirective;
status.timeout = $timeout(function() {
status.isActive = false;
}, 5000);
};
this.getStatus = function() {
return status;
};
}]);然后我在这样的指令中使用它:
core.directive('statusBox', ['statusHandler', function(statusHandler) {
return {
scope: {},
controller: 'MainCtrl',
controllerAs: 'core',
templateUrl: '/app/views/components/core/status-box.html',
link: function(scope, element, attrs, ctrl) {
scope.$watch(function() {
return statusHandler.getStatus();
}, function(newVal, oldVal) {
ctrl.status = newVal;
}, true);
}
};
}]);从这样的控制器调用resetStatus():
...
var completed;
... some logic to set completed to true ...
$scope.$watch(function() {
return completed;
}, function(newVal) {
if (completed) {
statusHandler.resetStatus();
statusHandler.setStatus('Videos have finished uploading and are now being processed', true, false);
}
});
...发布于 2016-01-08 09:12:19
在开始时在同一函数中分配一个新的超时之前,只需要清除之前的超时就可以解决这个问题。这就行了!
这似乎是某种函数范围问题,因为从resetStatus()调用函数没有做任何事情。
this.setStatus = function(message, isSuccess, isBoxDirective) {
$timeout.cancel(status.timeout);
status.message = message || 'Something went wrong';
status.isSuccess = isSuccess;
status.isActive = true;
status.isBoxDirective = isBoxDirective;
status.timeout = $timeout(function() {
status.isActive = false;
}, 5000);
};https://stackoverflow.com/questions/34672392
复制相似问题