Skip to content

Instantly share code, notes, and snippets.

@kyleschmolze
Created December 10, 2014 20:42
Show Gist options
  • Save kyleschmolze/93a510465e433c1981e1 to your computer and use it in GitHub Desktop.
Save kyleschmolze/93a510465e433c1981e1 to your computer and use it in GitHub Desktop.
Easy back button service for Ionic on Android
# I wanted to be able to easily add back button callbacks to certain app states
# (using the word "state" here in the context of ui-router).
# For example, I always know that the back button on page X should quit the app, etc.
# So I wrote this nifty service.
angular.module("groupmuse").service "BackButtonManager", ($rootScope, $ionicPlatform) ->
managedStates = []
$rootScope.$on '$stateChangeSuccess', (event, next) ->
# Disable all listeners
for state in managedStates
if state.enabled
state.unregisterCallback()
state.enabled = false
# Enable appropriate listener, if any
for state in managedStates
if next.name is state.name and !state.enabled
# registerBackButtonAction returns a function, which when called, disables the callback
state.unregisterCallback = $ionicPlatform.registerBackButtonAction state.callback, 100
state.enabled = true
break
return {
attachToState: (state, callback) ->
# Remove any existing managers for this state
managedStates = _.reject managedStates, (s) -> s.name is state
# Set up an object to manage each state
managedStates.push
name: state
callback: callback
enabled: false
}
# That's it, and you can use it like this (while initializing your app):
angular.module("your_app", [ "ionic"]).run (BackButtonManager) ->
BackButtonManager.attachToState 'app.events', ->
navigator.app?.exitApp() or navigator.device?.exitApp()
# Attach to as many states as you want!
@whitecat
Copy link

whitecat commented Jul 5, 2016

What would l need to write to make the back button not exit the app but go to the previous page?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment