我在第一个 Controller 中使用 $interval 来运行某些功能。重定向到第二个 Controller 后,$interval 注册函数(在第一个 Controller 中实现)仍在运行。我想在不使用 destroy 函数的情况下停止 $interval 服务。
最佳答案
Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.
您可以使用cancel
方法来清除$interval
对象。您应该在离开 Controller 时取消 interval
。
为此你需要在 $scope
的 $destroy
事件上添加 eventListener
,你可以做一些清理工作(例如取消间隔对象,取消超时对象)。
代码
var myInterval = $interval(function(){
//your interval code
}, 1000)
//register this listener inside your controller where the interval belongs.
$scope.$on('$destroy', function(){
$interval.cancel(myInterval)
});
关于javascript - AngularJs 停止特定 Controller 的 $interval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196098/