Handler for hardware back button exists on every view

For a view 'A' I have registered a controller like this.

myApp.controller(...{
    
    $ionicPlatform.onHardwareBackButton(function(event){
          alert("I am Page A")    
   })
})

For a view ‘B’ I have registered controller like this.

myApp.controller(...{
    
    $ionicPlatform.onHardwareBackButton(function(event){
        alert("I am Page B")    
   })

})

But this does not work properly. When I am in either View A or View B. Both the alerts fire. Example: If I am in View A and press back button, then I get two alerts. One is "I am page A" and the other "I am page b"

Its normal behaviour, it register handlers on general back button listener. But if you want to run specific code on each view you can easily do that with a simple if condition in your handler. For example:

myApp.controller('HomeController', function ($state, ...) {
  $ionicPlatform.onHardwareBackButton(function (event) {
    if ($state.current.name == 'home') {
      alert('Back on home');
    }
  });
});

myApp.controller('ProfileController', function ($state, ...) {
  $ionicPlatform.onHardwareBackButton(function (event) {
    if ($state.current.name == 'profile') {
      alert('Back on profile');
    }
  });
});