Reputation: 7743
In my AngularJs and phonegap/cordova application I listen for the back button event. I then broadcast this to certain controllers within my app.js:
document.addEventListener("deviceready", function(){
document.addEventListener('backbutton', function(){
$rootScope.$broadcast('backButton');
}, false);
}, false);
In certain views I want to listen to this so that I can inform the user that they will be quitting the app and give them the option to continue or not.
So there are two controls, lobby and game.
When a user clicks back in the lobby they should see a notification telling them they will be quitting the app:
$rootScope.$on('backButton', function(event){
$window.navigator.notification.confirm(
'Are you sure you want to exit app?', // message
$scope.exitApp, // callback to invoke
'APP', // title
['OK', 'Cancel'] // button labels
);
And if they hit OK they are logged out from the app and re-directed to the login screen.
When they are in the game view they should be informed they will be quitting their game and then redirected to the lobby:
$rootScope.$on('backButton', function(event){
$window.navigator.notification.confirm(
'Are you sure you want to quit your game?', // message
$scope.quitGame, // callback to invoke
'GAME', // title
['OK', 'Cancel'] // button labels
);
});
The issue I am seeing is that when I am in the game I see both notifications when I click the back button. One for the game which is correct but then an additional one for the lobby which is not needed.
So this is not really a defect, this is how it should work but being relatively new to Angular I am not sure of best approach as broadcast seems inappropriate here.
Upvotes: 0
Views: 2914
Reputation: 42669
$rootScope.$broadcast
is as the method implies a broadcasting mechanism. Whatever listeners are attach will get fired on broadcast, irrespective of where they are declared.
To fix it, you would have to determine first whether the controller related to lobby
should be in fact be loaded or not when game
controller is loaded. If the views for game and lobby are different and are not present in the same parent view, then lobby controller should not remain loaded when you are on game view. This is a typical memory leak.
In case both of them should be present, then in your handling methods on
you need to decide based on context which event handler to fire. You can make this decision using $route
or $location
service, which provide the current url\view (ng-view) in use.
Upvotes: 1