I new with app and angular.
My app use an interval to refresh the scope with a get request to the server. I want that interval to be cancel when the app goes to background.
I saw on other post '$onunload=function()' but i'm not sure if it is good or how to use it... I try: $scope.$onunload=function(){
// Make sure that the interval is destroyed when leaving app
$scope.stopRefresh();
};
but it didn't work.
Note that stopRefresh() function work with leaving tab, it cancel interval...
in other hand, is there some way that I can restart the interval whan coming back fro background?
here the full controler:
angular.module('starter.controllers', [])
main.controller("temperatureCtrl", ["$scope", "$rootScope", "$window", "$interval", "ArduinoService", function($scope, $rootScope, $window, $interval, service) {
$rootScope.arduinoServerUrl = '';
$rootScope.arduinoServerUrl = $window.localStorage['serverUrl'];
var autoRefresh;
$scope.channels = [];
function onTabSelected() {
$rootScope.arduinoServerUrl = $window.localStorage['serverUrl'];
}
$scope.options = {
loop: false,
//effect: 'fade',
speed: 500,
}
$scope.data = {};
$scope.$watch('data.slider', function(nv, ov) {
$scope.slider = $scope.data.slider;
})
function startRefresh() {
autoRefresh = $interval(function() {
updateAjax();
}, 5000);
}
function updateAjax() {
service.getChannels(function(err, result) { //get json data
if (err) {
return alert(err);
}
// puis les mets dans le scope
$scope.channels = result.channels;
})
};
$scope.init = function() { //on load page first get data
updateAjax();
//startRefresh()
}
$scope.stopRefresh = function() {
$interval.cancel(autoRefresh);
};
$scope.restartRefresh = function() {
startRefresh();
};
$scope.$on('$ionicView.leave', function() {
// Make sure that the interval is destroyed when leaving tab
$scope.stopRefresh();
});
$scope.$onunload=function(){
// Make sure that the interval is destroyed when leaving app
$scope.stopRefresh();
};
$scope.$on('$ionicView.enter', function() {
//star or restart interval scope update
$scope.restartRefresh();
});
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopRefresh();
});
}]);