2
votes

I am building a ionic pacakage, having multiple views. I use the route provider to navigate between different views.

app.js

.config(function($routeProvider,$locationProvider){

    $routeProvider
    .when('/search',
        {
            controller : 'MyController',
            templateUrl : 'partials/search.html'
        })

    .when('/not-found/:className',
        {
            controller : 'MyController',
            templateUrl : 'partials/not-found.html'
        })

My index.html

  <body ng-app="MyApp">  
        <ng-view></ng-view>

      </body>
    </html>

The problem is that the back button on my phone does not work.i.e it does not remember the history. e.g If I go from search.html to not-found.html, when I press the back button on my phone, I expect it to come back to search.html instead it closes my app. I looked and ionic forum and the suggest way to make back button work is to use ion-nav-view. If I replace ng-view with ion-nav-view, the search/not-found page are not rendering, I even tried adding the ion-view on the search/not-found html page.
1) Could you please suggest a way to get my back button working?

2

2 Answers

2
votes

In order to achieve that, you actually need to capture the hardware back button pressed event and perform the navigation accordingly or You can use ion-nav-back-button..

  1. Capture the hardware back button event :

    $ionicPlatform.registerBackButtonAction(function () {
      if (condition) {
        navigator.app.exitApp();
      } else {
        // handle back action!
      }
    }, 100);
    

More Details can be found here


  1. Using ion-nav-back-button

    <ion-nav-bar>
      <ion-nav-back-button class="button-clear">
        <i class="ion-arrow-left-c"></i> Back
      </ion-nav-back-button>
    </ion-nav-bar>  
    

More Details about this can be found here

0
votes

registerBackButtonAction is already handled as part of ion-nav-back-button as part of the ng-click attribute within the ion-nav-back-button definition: buttonEle.setAttribute('ng-click', '$ionicGoBack()') , since $ionicGoBack executes $ionicHistory.goBack() which in turn handles the hardware back button. A simple change to use state configuration should work fine as below:

angular
  .module('app', ['ionic'])
  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
     .state('search', {
        url: '/search',
        controller : 'MyController',
        templateUrl : 'partials/search.html'
    })
   .state('not-found', {
        url: `/not-found/:className',
        controller : 'MyController',
        templateUrl : 'partials/not-found.html'
    });

    $urlRouterProvider.otherwise('/search');        
  });

HTML:

<body ng-app="app">  
    <ion-nav-bar>
      <ion-nav-back-button></ion-nav-back-button>
    </ion-nav-bar>

    <ion-nav-view></ion-nav-view>
  </body>
</html>