javascript - 在 AngularJS 中打开新窗口或新选项卡时停止、启动和销毁间隔

标签 javascript angularjs

我有一个可以正常工作并且破坏良好的间隔,但是当我导航到新窗口或新选项卡时,警报也会显示在那里。如何停止此警报?

$scope.checkGuest = function() {
  $http.get(url + 'c_chat/checkGuestJson').success(function (data) {
    $scope.guestAlerts = data
    console.log(data);
    if(data == 1) {
      alert('plz register to enjoy more features');
    } 
    else {
      alert('plz register ! after 10 minutes your contact will be deleted');
    }
  })
}

我已经将间隔设置为11分钟

var intervalPromise = $interval(function () {
  $scope.checkGuest() 
}, 660000);      

$scope.$on('$destroy', function () { 
  $interval.cancel(intervalPromise); 
})

当路线更改时,不会显示警报,这是正确的,但当打开新选项卡时,会显示警报,这是我不喜欢的

 app.config(function ($routeProvider) {
   $routeProvider.when('/c_chat', {
     template: '<div class="gusestAlert"></div>',
     controller: app.chatCtrl
   });
 }

最佳答案

这里的问题是,如果您在新选项卡中打开链接,则不会触发 $destroy 监听器,因为 Angular 范围仍然“事件”。

您可以在此处执行的操作是在每次打开新选项卡时强制调用监听器。

例如

$scope.$on('$destroy', destroyInterval); //called by angular
$rootScope.$on('$destroyInterval', destroyInterval); //generic listener

function destroyInterval(){ 
  $interval.cancel(intervalPromise); 
})

<a href="/something" target="_blank" ng-click="$root.$emit('$destroyInterval') ">
  go to new tab </a>

关于javascript - 在 AngularJS 中打开新窗口或新选项卡时停止、启动和销毁间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43980868/

相关文章:

javascript - 全局安装 Sails.js 出现依赖错误

javascript - 如何在 RequireJS 中定义 "main"脚本的类型

javascript - ES6 没有类的子类数组

angularjs - typings.json 没有更新 typings install --ambient

javascript - 如何使用 javascript 或 Angular 将一个数组的每个元素添加到其他数组中的相应元素

javascript - 递归计算出现次数

javascript - Angular : Selectively compile templates

javascript - 如何使用 nvd3 触发调整大小事件?

javascript - Kendo UI 网格 - 分组表标题

javascript - 通过 ng-repeat 单击访问 li 数据