Search code examples
cordovadialogback-buttononsen-ui

How to handle hardware Back Button on Ons-Dialog?


My app contain ons-dialog on a imageclick that opens image in a dialog.But I am unable to handle hardware device back button.It is showing error of 'Capturing Back button handler is failure.So how to do it???Please help.

Code :

<ons-template id="ImagePopup.html">

  <ons-dialog style="height:100%;width:100%;background:#000000;" var="naviDialog" cancelable ng-device-backbutton="click();" animation="fade" true> 
     <img id="PopImg" style="height:50%;width:100%;padding-top:30%">

  </ons-dialog> 

</ons-template>

Solution

  • I had the same problem when using the dialog component from within an ons-navigator object. In order to make it work, I had to disable the default back button handler of the dialog and have the Navigator object handle it instead.

    Here is the code I made, hope it helps:

    ons.createDialog('dialogs/yourDialog.html').then(function(dialog) {
        dialog.getDeviceBackButtonHandler().disable();
    
        var f = function(event) {
            dialog.hide();
            myNavigator.getDeviceBackButtonHandler().setListener(function(event) { 
                try{
                    myNavigator.popPage(); 
                }
                catch (err){
                    event.callParentHandler();
                }
            });
        } 
        myNavigator.getDeviceBackButtonHandler().setListener(f);
        dialog.show({parentScope: $scope});
    });
    

    Brief explanation:

    • Disable dialog back button handler (this is what is causing errors)
    • When disabled, the back button will be handled by the next node that has a back button handler (myNavigator, in this case) that works fine.
    • Change the event listener of myNavigator when the dialog is shown, to hide the dialog.
    • After hiding it, I try to restore its default functionality. It´s a Navigator object, so popPage should be the default action, and, if the page stack is empty (what throws an error) we will call the parent handler (that will, usually, get you out of the app)