Trigger some code when back button is pressed

How do i capture when back button is pressed?
THis back button is automatically shown when navigated to child view.

I have a form on this page, and want to save the form when back button is pressed (physical button or even the back icon shown on the left top corner).

I don’t want to save the object when any form field is changed, so was thinking to save the form when back button is pressed. (not sure whether this is the right way to save the changed form in angularjs though…).

If someone can point me a better way to save the form when any changes from user are done, please point me the right direction (I don’t want to put “submit” button on the view for user to click — I want implicit save when done).

Thanks! Ionic rocks!

What I did was to remove the default back button (using hide-back-button=“true” in your view) then add the right buttons (left-buttons=“leftButtons” in your view) and in the controller you set the right button

$scope.leftButtons = [{ 
        content: '<i class="button back-button button-icon icon ion-arrow-left-c no-padding"></i>',
        tap: function(e) {
            //Do what you want here

There may be some padding issues that’s why i have a class to remove the padding. And be sure to add use $window.history.back(); to go back once you’re done. The only problem is when it comes to the android back button. You could use the cordova function

// do something

I’m actually stuck there, i want to prevent the default behaviour of the android back button, but it will go back in the history no matter what I do. But i think it will work for you. Hope that helps!

But with this solution you will lose the back button enter animation

Look at stateChangeStart. This will allow you to detect when the state is changing due to the back button press. Then, you can save the form data to a service.

Alternatively, you could use $watch on the form’s model. Then, every time the user types, the watch event is triggered. You save as they type.

You could also use ng-change on each form element to save as the model changes.

1 Like