2017-12-27 980 views
0

我有一个按钮,点击(ng-click),调用$ interval。如果我回到包含带有浏览器后退按钮的按钮的状态,则会再次调用$ interval。这是一个问题,因为间隔是$ state.go()的计时器,并且会再次更改状态。

我的代码如下。任何人都可以解释为什么会发生这种情况,我可能会重写这个以允许通过浏览器向后导航而不触发$ interval。提前致谢。

控制器:

angular.module('app') 
    .component('splash', { 
     templateUrl: '/templates/splash.template.html', 
     controller: SplashController 
    }) 

    SplashController.$inject = ['SplashService', '$http', '$stateParams', '$state', '$interval'] 

    function SplashController(SplashService, $http, $stateParams, $state, $interval) { 
    console.log("you are in the splash Controller") 
    const vm = this 
    vm.$onInit = onInit 
    vm.userAuth = {} 
    function onInit() { 
     // $(".button-collapse").sideNav() 
    } 
    vm.logIn = function() { 
     console.log('userAuth: ', vm.userAuth) 
     SplashService.logIn(vm.userAuth) 

    } 

    vm.moveLotus = function() { 
     let lotus_top = document.getElementById('animated-login-top') 
     let lotus_bottom = document.getElementById('animated-login-bottom') 
     // let menuIcon = document.getElementById('menuIcon') 
     // menuIcon.style.display = 'none' 
     lotus_top.className = 'animated-login-top-move move-lotus-top' 
     lotus_bottom.className = 'lotus-login-bottom-pulse move-lotus-bottom' 
     // wait 2 seconds and then &state.go('feed') 
     let goTo = function(state) { 
     $state.go(state) 
     } 
     $interval(function() { 
     goTo('feed') 
     }, 2500) 
    } 
    } 

HTML:

<div class="row demoRow center"> 
    <a href="#" ng-click="$ctrl.moveLotus()">Demo Site</a> 
</div> 

回答

1

是的,在这种情况下$interval仍然有效,您应该通过手动$interval.cancel停止时$scope.$on('$destroy'...

angular.module('app', []) 
 
    .controller('ctrl', function($scope, $interval) {   
 
    var stopTime = $interval(function() {  
 
     console.log(new Date()); 
 
    }, 1000); 
 

 
    $scope.$on('$destroy',() => { 
 
     $interval.cancel(stopTime); 
 
    }); 
 
    })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app='app'> 
 
    <button ng-click='show=!show'>{{show ? 'Destroy' : 'Create'}} controller</button> 
 
    <div ng-controller='ctrl' ng-if='show'>   
 
    controller 
 
    </div> 
 
</div>

P.S.在您的具体情况下,最好使用$timeout而不是$interval

+0

这不起作用。当浏览器导航回到状态时,我无法手动销毁问题。我甚至试着在我的$ onInit函数中运行'''$ interval.cancel(goToFeed)''来进行状态加载,但是这也不起作用。 – MrJonesIsMe

相关问题