AngularJs & Ionic: Stop / Restart $ timeout when changing and returning to view

I have a View that updates after 1 minute, I stop the timer after you leave this view, and everything is fine. After returning to the current view, the timer does not restart again.

This is the controller code of this kind:

.controller('IndexCtrl', function($scope, $timeout, RestService) { var updateN = 60*1000; $scope.test = "View 1 - Update"; var update = function update() { timer = $timeout(update, updateN); /** make a http call to Rest API service and get data **/ RestService.getdata(function(data) {; $scope.items = data.slice(0,2); }); }(); /** Stop the timer before leave the view**/ $scope.$on('$ionicView.beforeLeave', function(){ $timeout.cancel(timer); //alert("Before Leave"); }); /** Restart timer **/ $scope.$on('$ionicView.enter', function(){ $timeout(update, updateN); //alert("Enter"); }); }) .controller('ViewCtrl2', function($scope) { $scope.test = "View 2"; }); 
+7
angularjs ionic-framework ionic ionic-view
source share
3 answers

I solve the problem, There is no problem in the cache, but with updating the function, which is not called after re-entering the page. I move the update function inside $ ionicView.enter: Corrected code:

  $scope.$on('$ionicView.beforeLeave', function(){ //updateN=12000000; $timeout.cancel(timer); //alert("Leave"); }); $scope.$on('$ionicView.enter', function(){ //updateN=12000000; var update = function update() { timer = $timeout(update, updateN); RestService.getdata(function(data) { //console.log(tani); //$scope.items = data; $scope.items = data.slice(0,2); }); }(); }); 
+4
source share

When you return to the current view, it comes from the cache, so the controller does not work again. You can disable caching in the configuration section of your application by adding this line of code:

 $ionicConfigProvider.views.maxCache(0); 

or you can disable the cache on a specific view in the routing part by adding cache: false.

More here and here

0
source share

In your code, the function of your controller does not cause a view change. Call the $ timeout function outside of the var update function. Each time a view is loaded, it calls its controller and calls anonymous or self-executing functions in its area.

 .controller('IndexCtrl', function($scope, $timeout, RestService) { var updateN = 60 * 1000; $scope.test = "View 1 - Update"; var update = function update() { var timer = $timeout(update, updateN); /** make a http call to Rest API service and get data **/ RestService.getdata(function(data) {; $scope.items = data.slice(0, 2); }); }(); /** Stop the timer before leave the view**/ $scope.$on('$ionicView.beforeLeave', function() { $timeout.cancel(timer); //alert("Before Leave"); }); /** Restart timer **/ $scope.$on('$ionicView.enter', function() { timer() }); 

})

.controller ('ViewCtrl2', function ($ scope) {

 $scope.test = "View 2"; 

});

-one
source share

All Articles