检测angularjs路由控制器何时超出范围?

时间:2021-10-02 01:56:49

I have a controller that is attached to a route. The controller constantly polls the server using $timeout. When the route changes, I need to stop polling, and start it again when the route changes back.

我有一个连接到路线的控制器。控制器使用$ timeout不断轮询服务器。当路线改变时,我需要停止轮询,并在路线改变时再次启动它。

Please help.

Here is my code:

这是我的代码:

(angular
 .module('app.controllers', ['ng', 'ngResource'])
 .controller('myContr', [
     /******/ '$scope', '$resource', '$timeout',
     function ($scope,   $resource,   $timeout) {
         function update() {
             $resource('my-service').get({}, function (d) {
                 // ...use data...
                 $timeout(update, UPDATE_INTERVAL);
             });
         };
         update();
     }
 ])
);

1 个解决方案

#1


3  

  • Save the return value (a promise) from $timeout (to a $scope property).
  • 从$ timeout(到$ scope属性)保存返回值(一个promise)。

  • Register a $destroy event handler on your scope.
  • 在您的作用域上注册$ destroy事件处理程序。

  • Call cancel() on that $timeout promise when the event handler triggers.
  • 当事件处理程序触发时,在$ timeout promise上调用cancel()。

When the route changes back, the controller will get recreated, so your existing code should start up the polling again.

当路由更改回来时,控制器将重新创建,因此现有代码应该再次启动轮询。

#1


3  

  • Save the return value (a promise) from $timeout (to a $scope property).
  • 从$ timeout(到$ scope属性)保存返回值(一个promise)。

  • Register a $destroy event handler on your scope.
  • 在您的作用域上注册$ destroy事件处理程序。

  • Call cancel() on that $timeout promise when the event handler triggers.
  • 当事件处理程序触发时,在$ timeout promise上调用cancel()。

When the route changes back, the controller will get recreated, so your existing code should start up the polling again.

当路由更改回来时,控制器将重新创建,因此现有代码应该再次启动轮询。