Going back programmatically


How can I go back (emulating the ion-nav-back-button action) programmatically in my controller? I want to do this in case of error of a http call.

Just to clarify: I don’t want to go to parent state, I want to go to the previous one.

function SomeController($scope, $ionicNavBarDelegate) {
  var goBack = function() {

Reference could be found here: http://ionicframework.com/docs/api/service/$ionicNavBarDelegate/


Thanks! Sorry for my lousy previous-asking search…


No problemo :slight_smile: Was pretty busy so couldn’t write a decent answer, but thought you’d be happier with a very short to the point answer than with waiting few hours and get a polite answer haha :stuck_out_tongue:


Another option could be:

function() {
        var backView = $ionicViewService.getBackView();
            //Can’t go back, no back view

Does anybody know which one is best way of doing it?



It depends on your goal really. If you “just” want to move back in history, the solution with the $ionicNavBarDelegate should be fine. But if you want to control what happens based on the previous view, the $ionicViewService is the way to go!

function SomeController($scope, $ionicNavBarDelegate) {
  //Just go back
  var goBack = function() {

  //Go back conditionally
  var goBackIfWeCameFromHomeView = function(){
       var backView = $ionicViewService.getBackView();
        if(backView == homeview ){ //optimize this check so it's actually correct
            alert('We didn't come from the homeview so you shouldn't have used this method');
            //Or something else what you would want to do.


Looks like back() has been deprecated.


I get the following error when calling back()
TypeError: Illegal invocation
at deprecatedWarning (http://localhost:8100/lib/ionic/js/ionic.bundle.js:47077:13)
at IonicModule.controller.self.back


I get the depreciated error too, it gives this warning:

warn navBarController.back() is deprecated, please use $ionicHistory.goBack() instead

Currently the cleanest way of going back programmatically IMO:

// run this function when either hard or soft back button is pressed
var doCustomBack = function() {
    console.log("custom BACK");

// override soft back
// framework calls $rootScope.$ionicGoBack when soft back button is pressed
var oldSoftBack = $rootScope.$ionicGoBack;
$rootScope.$ionicGoBack = function() {
var deregisterSoftBack = function() {
    $rootScope.$ionicGoBack = oldSoftBack;

// override hard back
// registerBackButtonAction() returns a function which can be used to deregister it
var deregisterHardBack = $ionicPlatform.registerBackButtonAction(
    doCustomBack, 101

// cancel custom back behaviour
$scope.$on('$destroy', function() {

Then in your doCustomBack() you can $state.go('app.somewhere')

Reference: http://stackoverflow.com/questions/32231737/ionic-override-all-back-button-behaviour-for-specific-controller