执行取消$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);
}
});
...
答案 0 :(得分:2)
通过在开始时在同一函数内分配新超时之前清除先前的超时来管理解决它。这诀窍!
它似乎是某种功能范围问题,因为从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);
};