AngularJS的$destory用法

在controller中监听$destory事件,这个事件会在路由发生跳转的时候触发。
用法:

$scope.$on("$destroy", function() {
    //清除配置,不然scroll会重复请求
  })

常用到的地方是,在页面建立计时器的时候,跳转其它页面,这个计时器依然还在执行,第二次进入这个页面,会重复创建计时器,所以就需要这个方法,监听离开当前路由的时候,销毁当前页面的所有计时器;

//controller 里面建立一个计时器,最后需要写一监听销毁的方法
var testTimer = $interval(function(){
    console.log(1);
},1000)



$scope.$on("$destroy", function() {
   //离开路由时,清除计时器
   $interval.cancel(testTimer);
 })

猜你喜欢

转载自blog.csdn.net/m0_37885651/article/details/80019423