在angularjs中导航期间的停止时间间隔

Stop time interval during navigation in angularjs

本文关键字:时间 导航 angularjs      更新时间:2024-04-01

当前我使用的是angular js

我有一种在default.html页面中从服务器端获取数据的方法

function bindActiveLoans() {
            $http.get(rootUrlSingleEscaped + '/cooperativa/allunfundedloans/?authId=' + userInfo.UserId)
                 .success(function (response) {
                     if (response.Loans.length == 0) {
                         $scope.IsValues = false;
                         $scope.$apply();
                         return true;
                     }
                     $scope.IsValues = true;
                     $scope.unfundedLoans = response;
                 });
        };
        setInterval(function () {
            $scope.$apply(bindActiveLoans());
        }, 5000);

上述功能有助于每5秒从服务器端方法获取数据。

这里,我有一个问题。

另外,我还有一些页面,比如

  • default2.html、default3.html、default4.html、default5.html.

    当我将default.html页面导航到default1.html页面时,计时器仍在运行。我只想让计时器在default.html页面中运行。如果我转到另一页,那么计时器应该停止。我们如何才能做到这一点?

来自$interval API页面中的angularjs示例。

    var interval = $interval(function() {
        console.log('say hello');
    }, 1000);
    $interval.cancel(interval);

使用$interval.cocancel(var),您可以停止间隔,如果您想在导航到另一个页面时停止它,您应该尝试这样的操作。

var interval = null;
module.controller('SomeController', '$interval', function($interval) {
    interval = $interval(function() {
        ...
    }, 2000);
}).run(['$rootScope', '$interval', function($rootScope, $interval) {
    $rootScope.$on('$routeChangeStart', function() {
        $interval.cancel(interval);
    });
}]);

您可以监听$routeChangeStart事件并根据路由参数清除间隔

  $scope.$on('$routeChangeStart', function (scope, next, current) {
           if(<next is not default.aspx>){
           // clear interval here
            }
  });

从默认页面导航时调用clearInterval函数

例如

var myVar = setInterval(function () {
        $scope.$apply(bindActiveLoans());
    }, 5000);

function myStopFunction()
{
clearInterval(myVar);
} 

调用myStopFunction