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.

var onDeviceReady = function(){
   document.addEventListener("backbutton", handleDeviceBackButton, false);
}
function handleDeviceBackButton(){
	/* write you code here */
}

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.

var onDeviceReady = function(){
   document.addEventListener("backbutton", handleDeviceBackButton, false);
}

This is the callback method for backbutton event.

function handleDeviceBackButton(){
	 /* write you code here */
}

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

document.addEventListener("deviceready", onDeviceReady, false);

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

function handleDeviceBackButton(){
	angular.element('[ng-controller=AppCtrl]').scope().goHome();
}

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

<body ng-controller="AppCtrl">

Now include the following code in your AppCtrl method.

function AppCtrl($scope, $location) {
    $scope.goHome = function () {

        if ((window.location) && (window.location.hash) && (window.location.hash.indexOf('home') > 0)) {
            navigator.app.exitApp();   // This will exit the application
        }
        else {
            $location.path('/home');  // This will redirect the application to home page

            if (!$scope.$$phase)
                $scope.$apply();
        }
    }	
}

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 *