在 angular 中,如何对用户事件(如页面更改)使用取消 $interval? [英] In angular, how to use cancel an $interval on user events, like page change?

查看:17
本文介绍了在 angular 中,如何对用户事件(如页面更改)使用取消 $interval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 文档关于 $interval 说:

<块引用>

注意:此服务创建的时间间隔必须在您完成后显式销毁.

但它没有解释如何销毁 $interval.

例如,如果我有一个包含此代码的指令:

$interval(function() {for (var i in myArray) {//做一些事情}}, 5000);

例如,当用户更改页面时,我如何销毁它?

解决方案

每当用户更改页面时,与路由控制器关联的作用域(下例中的/page1)将变为发送了一个$destroy 事件.您可以在该事件的侦听器中cancel $interval :

app.config(function ($routeProvider) {$routeProvider.when('/page1', {模板:'

页面内容

',控制器:页面控制器});//...});函数 PageController($scope, $interval) {var intervalPromise = $interval(function () {/* ... */}, 5000);$scope.$on('$destroy', function () { $interval.cancel(intervalPromise); });}

Angular documentation about $interval is saying :

Note: Intervals created by this service must be explicitly destroyed when you are finished with them.

but it's not explaining how to destroy the $interval.

If for example I have a directive containing this code :

$interval(function() {
    for (var i in myArray) {
        // do domething
    }
}, 5000);

How can i destroy it when the user changes the page for example?

解决方案

Whenever the user changes the page, the scope associated with the controller of the route (/page1 in the example below) will be sent a $destroy event. You can cancel that $interval in a listener to that event:

app.config(function ($routeProvider) {
     $routeProvider.when('/page1', {
          template: '<div>Page Content</div>',
          controller: PageController
      });
     // ...
});

function PageController($scope, $interval) {
    var intervalPromise = $interval(function () { /* ... */ }, 5000);      
    $scope.$on('$destroy', function () { $interval.cancel(intervalPromise); });
}

这篇关于在 angular 中,如何对用户事件(如页面更改)使用取消 $interval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆