Android back and menu button simplified


#1

I need to handle the Android back button. And I cant find a straight forward way or code sample on how I can use the $ionicPlatform to control my app. Look at it this way. I want the press of that button to allow the user to go back one view other than going to all the views they have been to. Its crazy if you know what I mean. Please tell me where I need to put the code. How to implement it and so on.

E.g. Use it in the controller like

app.controller('mainCtrl',function($ionicPlatform,$scope){ ... });

If you can also help me with how I can handle the press of the menu button. Thanks for your help.
Martin


#2

You would register a custom function on back button press. Something like this would work.

$ionicPlatform.registerBackButtonAction(
  function () {
    alert("Some custom function here")
  }, 1
);

This way it takes effect of the defaults ionic has set up


#3

I have no Idea where this will be placed. In the controllers? Like I asked. Can you give me an example on how you implemented this function? Thanks for your reply


#4

Yes, in a controller.

You would do something like this.

.controller('MyCtrl', function($scope,$ionicPlatform){ 
  $ionicPlatform.registerBackButtonAction(
    function () {
      alert("Some custom function here")
    }, 1
  );
});

Then attach the controller to the body element


#5

So If I give the function a return false, eg:

$ionicPlatform.registerBackButtonAction(function(){ return false;},1); 

I will still have my application working right? No more flinging to all the pages the user has been to? Sorry for many questions but you will really save me a lot of time here. I choose this framework because of its simplicity and awesomeness. :slight_smile: Thanks @mhartington


#6

You shouldn’t need to use return false. Since is being executed at priority 1, it will take effect over the default back behavior (AFAIK),


#7

Thanks. I will implement it tomorrow since here its 0200Hrs now (Nairobi). I will post back with results. Thank you again for your help.