【问题标题】:How to stop a setInterval function from executing on an angular directive after route change如何在路由更改后停止 setInterval 函数在角度指令上执行
【发布时间】:2015-01-27 05:47:38
【问题描述】:

我正在通过指令将画廊放入页面。画廊使用 javascript 在图像之间来回解析(我计划使用 css 转换来旋转通过一组类)。

我想要一个 setInterval 函数执行,但只有当指令在页面上时(也就是说只有在调用某个路由时)。但是,即使点击了新路由,并且在我的页面上呈现了新视图,现有功能仍在执行。例如:

指令:

angular.module('app')
  .directive('gallery', function ($location) {
    return function (scope, element, attrs) {
      setInterval(function () {
        //This is where I would change the classes on the element
        //This will continually execute, even when on a different view
      }, 500);
    }
  });

HTML 视图

<div gallery>
    Something special
</div>

有没有什么办法让我只在指令在页面上时执行间隔函数?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

您可以取消$destroy 事件的间隔。

var intervalPromise = $interval(function() {
  // do your operation
}, 500);

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

这里是文档的链接:https://docs.angularjs.org/guide/directive

【讨论】:

  • $interval 返回一个承诺,而不是 timeoutId。更改变量名,答案会更清晰。
  • @NewDev,我只是从官方文档中获取的。你确定这是承诺吗?
【解决方案2】:

你应该使用 $interval:-

    var promise=$interval(function () {

    }, 500);
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 

        if(next!=current)
            $interval.cancel(promise);

    });

或者如果你使用 setInterval:-

var promise=setInterval(function () {
      }, 500);
$rootScope.$on("$locationChangeStart", function(event, next, current) { 

        if(next!=current)
           clearInterval(promise);

    });

【讨论】:

  • 这对我来说是正确的。为什么使用 $interval 而不是原生 javascript 是一个更好的主意?
  • 因为它是一种角度的方法。它在角度的 $apply() 循环内工作。
  • 这不是一个好的解决方案,因为它将您的指令与应用程序如何更改视图联系在一起。看看@UlanMurzatayev 的答案,它提供了更强大的方法
  • 无需关注 $locationChangeStart 事件,您只需关注 $destroy 事件被触发即可。每当从 DOM 中删除元素时都会触发它。
  • 好的,所以我们必须在指令中找到视图已更改,而不是列出视图..??在 $destroy 的帮助下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2021-12-05
  • 2016-09-01
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
相关资源
最近更新 更多