handling android device back button with phonegap and angular js

The mobile application which we developed using phonegap (cordova-2.7.0) and Angular JS have a requirement that, on tapping the device back button from any page, the application should redirect to home page and if the user taps the device back button from home page, application should exit.

I could find a lot of websites which says that, we can control the device back button using phonegap and then, they just pasted the code from phonegap’s official website, like given below.

There is no good example available, which drives me crazy.

Hence, I thought of sharing this small example, which might be helpful for so many developers who is searching for a solution for handling android device back button with phonegap and angular js.

This is how it works.

In your angular project, the javascript file (lets call it as app.js) where you write your directive, config etc, just add the codes mentioned below.

This is the callback method for backbutton event.

This code will register the deviceready event. Once the device is ready, the callback method onDeviceReady will be called.

Now, All the above code is lying outside the scope of Angular. We can’t do anything without getting the scope. How do we get it.

Add one line to the handleDeviceBackButton() method. Then, the code will look like

What is happening here?

We are trying to get the scope of an element which have the attribute ng-controller=”AppCtrl” and calling the method goHome, which is withing the scope of this element.

In my application, it is the body element

Now include the following code in your AppCtrl method.

Any suggestions or code improvements are welcome.

4 Replies to “handling android device back button with phonegap and angular js”

Leave a Reply

Your email address will not be published. Required fields are marked *