2017-12-27 29 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는 여전히 작동이 경우에, 당신은 수동으로 할 때 $scope.$on('$destroy'...$interval.cancel를 통해 중지해야합니다

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. 특정 경우에는 아마도 $interval 대신 $timeout을 사용하는 것이 좋습니다.

+0

이것은 작동하지 않습니다. 브라우저가 상태를 다시 탐색 할 때 문제가 발생하면 수동으로 삭제할 수 없습니다. 나는 state load를위한 $ onInit 함수 내에서'''interval.cancel (goToFeed)'''를 실행하려고 시도 했었지만, 이것은 역시 작동하지 않는다. – MrJonesIsMe