如何仅在离开 AngularJS 中的状态时取消 $interval?
How do I cancel $interval only on leaving a state in AngularJS?
这个想法是让模式在用户进入特定页面 10 秒后在特定页面上打开,如果用户离开该页面则取消它。它在我刷新页面时有效,但是当我导航到该页面时,我的代码在加载时取消了 $interval。
在我的控制器中:
$rootScope.$on("$locationChangeStart", function(event, next, current) {
$interval.cancel(interval);
});
$scope.openmodal = function () {
interval = $interval(function () {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modal.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
});
}, 10000, [1]);
}
$scope.openmodal();
问题是当从不同的状态加载状态时执行 $locationChangeStart。当我刚刚刷新浏览器时,$locationChangeStart 不会 运行 并且模式将在 10 秒后打开。从不同状态加载时如何阻止我的控制器调用 $interval.cancel() 方法?
$scope.$on('$stateChangeSuccess', function() {
$interval.cancel(interval);
});
请阅读 ui-router
的文档,特别是 events 部分。
每次在状态控制器中加载新状态时,您都需要启动计时器。如果用户保持在 state ,将显示模态。
但是,如果用户在打开模式之前离开状态,则需要取消计时器,因为新状态将再次启动计时器的新实例。
$scope.$on('$destroy', function() {
$interval.cancel(interval);
});
var interval = $interval(function () {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modal.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
});
}, 10000, [1]);
这个想法是让模式在用户进入特定页面 10 秒后在特定页面上打开,如果用户离开该页面则取消它。它在我刷新页面时有效,但是当我导航到该页面时,我的代码在加载时取消了 $interval。
在我的控制器中:
$rootScope.$on("$locationChangeStart", function(event, next, current) {
$interval.cancel(interval);
});
$scope.openmodal = function () {
interval = $interval(function () {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modal.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
});
}, 10000, [1]);
}
$scope.openmodal();
问题是当从不同的状态加载状态时执行 $locationChangeStart。当我刚刚刷新浏览器时,$locationChangeStart 不会 运行 并且模式将在 10 秒后打开。从不同状态加载时如何阻止我的控制器调用 $interval.cancel() 方法?
$scope.$on('$stateChangeSuccess', function() {
$interval.cancel(interval);
});
请阅读 ui-router
的文档,特别是 events 部分。
每次在状态控制器中加载新状态时,您都需要启动计时器。如果用户保持在 state ,将显示模态。 但是,如果用户在打开模式之前离开状态,则需要取消计时器,因为新状态将再次启动计时器的新实例。
$scope.$on('$destroy', function() {
$interval.cancel(interval);
});
var interval = $interval(function () {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modal.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
});
}, 10000, [1]);