更改路线时,$ interval功能会继续

Muk*_*mar 6 angularjs

$interval当我改变路线时,我的问题仍然存在.

这是代码:

  x = 2;

 var multiply = function () {
     x = x * 2;
     if (x == 134217728) {
         $interval.cancel($scope.stop);
         $scope.stop = 0;
     }
 }


 $scope.Result = function () {
     $scope.stop = $interval(multiply, 1000);
 }

 $scope.Result();
Run Code Online (Sandbox Code Playgroud)

什么时候x<134217728,我改变路线移动到另一页.问题是$interval路线改变后不会停止.我将promise存储stop$scope模型中的变量中.我认为$scope在路线改变后不会破坏,这就是$interval继续的原因.

我该如何解决这个问题?

rye*_*lar 14

您可以在控制器/服务中调用$interval.cancel($scope.stop);when $locationChangeSuccess.

例如

controller('MyController', function($rootScope, $interval) {
  $scope.stop = $interval(yourOperation, 1000);

  var dereg = $rootScope.$on('$locationChangeSuccess', function() {
    $interval.cancel($scope.stop);
    dereg();
  });

  function yourOperation() {}
};
Run Code Online (Sandbox Code Playgroud)

  • 还有一个更普遍有用的$ destroy事件:http://odetocode.com/blogs/scott/archive/2013/07/16/angularjs-listening-for-destroy.aspx (2认同)