Reputation: 8075
Let me say I have a piece of code like this inside a controller, in an Angular/Ionic app:
$scope.$on('$ionicView.beforeEnter', function() {
setTimeout(function() {
myFunction();
}, 5000)
});
when the user leaves the url mapped to this controller before this 5 seconds from the timeout, the script doesn't stop (and it makes sense). My problem is: myFunction()
opens an ion-modal.
When the user leaves the page and another one is rendered. But myFunction() will be triggered when the other view is rendered and, then, the ion-modal from the previous view will be shown in the new view. I'm using setTimeout()
for this example because in my code myFunction()
is called after an ajax request (and I have no control on the response time).
Is there a way to prevent the current script to execute inside the ionicView.leave event?
EDIT: I found out that $scope has an attribute $$disconnected set to true when the view is left. Do I have to check whether this value is true or not inside my function, to open or not the modal? And, if I have 'n' async functions, do I have to check this inside all my 'n' functions?
EDIT II: I achieved a solution wrapping myFunction() inside a $timeout, assigning its return to a variable and then and on the ionicView.leave, cancelling it:
modaltimeout = $timeout(function() { myFunction(); )};
$scope.$on('$ionicView.leave', function() {
$timeout.cancel(modaltimeout);
});
So, regardless what is inside myFunction(), the promise is cancelled and nothing else happens :-)
Upvotes: 0
Views: 2039
Reputation: 545
you need to add your check to handler:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {...}
Upvotes: 0
Reputation: 2486
so first name your timeout function:
$scope.$on('$ionicView.beforeEnter', function() {
myVar = setTimeout(function() {
myFunction();
}, 5000)
});
in your controller simple add a
$scope.$on('$ionicView.beforeLeave', function(){
clearTimeout(myVar);
});
Then when you leave your view your timeout will be cleared.
EDIT!
you can control when a function is called after a http request by using the .then callback. It will be run after your ajax call has finished. Here is a example.
var req = {
url: 'https://yoururl.com',
method: "GET",
headers: {}
}
$http(req).success(function(data, status, headers, config){
}).error(function(data, status, headers, config){
}).then(function(data, status, headers, config){
//put code here to run after the http call
})
EDIT 2:
in the .then() part of the call back simply check what state is loaded using
$ionicHistory.currentStateName()
so it will look like
.then(fucntion(data, status, headers, config){
if($ionicHistory.currentStateName() === "about"){
//open modal
}
})
check to see if you are in the about view. if you are pull up the modal, if not dont. Easy peasy lemon squezzy. See more about checking the state/view here http://ionicframework.com/docs/api/service/$ionicHistory/
Upvotes: 0