执行取消$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);
}
});
...
设法通过在开始时在同一函数中分配新的超时之前清除以前的超时来解决它。哪个能解决问题!
这似乎是某种函数范围问题,因为从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);
};