2017-12-27 463 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