綁定到物理後退按鈕,你可以使用:
document.addEventListener("backbutton", $scope.goBack, false);
要做到這一點,你需要在你的控制器使用組合角$窗口和$位置服務。我建議不要覆蓋你的$父範圍函數,因爲你可能在另一個頁面上出現奇怪的行爲。另外,請注意,您不允許在iOS設備上退出或暫停您的應用。看到一些示例代碼如下:
var AppCtrl = ['$scope', '$window', '$location', '$timeout', '$notification', '$rootScope', function ($scope, $window, $location, $timeout, $notification, $rootScope) {
'use strict';
// Somewhere inside AppCtrl
$scope.checkExit = function() {
// https://stackoverflow.com/questions/14422908/iphone-does-not-recognize-phonegaps-navigator-app
// fack!!!
if ($location.path() == '/home' && !$scope.isIOS) {
$notification.confirm("Exit application?", function(result) {
if ($window.isPhoneGap && result == 1) {
$rootScope.$broadcast('appExit'); // ga tracking
navigator.app.exitApp();
}
});
return true;
}
return false;
};
$scope.goBack = function (evt) {
if (evt != null) {
if (evt.preventDefault) {
evt.preventDefault();
}
}
if (!$scope.checkExit()) {
$window.history.back();
}
};
document.addEventListener("backbutton", $scope.goBack, false);
}]; // End AppCtrl
// in some other file, I have $notification friendly factory
app.factory('$notification', ['$rootScope', '$window', function ($rootScope, $window) {
return {
alert: function(message) {
if (!$window.isPhoneGap) {
$window.alert(message);
return;
}
navigator.notification.alert(message, null, '', 'OK');
},
confirm: function (message, callbackFn, title, buttonLabels) {
if (buttonLabels == null) {
buttonLabels = 'OK,Cancel';
}
if (!$window.isPhoneGap) {
callbackFn($window.confirm(message) ? 1 : 2);
return;
}
navigator.notification.confirm(
message, // message
callbackFn, // callback to invoke with index of button pressed
title, // title
buttonLabels.split(',') // buttonLabels
);
},
prompt: function (message, callbackFn, title, defaultText, buttonLabels) {
if (buttonLabels == null) {
buttonLabels = 'OK,Cancel';
}
if (defaultText == null) {
defaultText = '';
}
if (!$window.isPhoneGap) {
var answer = $window.prompt(message, defaultText);
callbackFn({
buttonIndex: (answer ? 1 : 2),
input1: answer
});
return;
}
navigator.notification.prompt(
message, // message
callbackFn, // callback to invoke
title, // title
buttonLabels.split(','),
defaultText
);
}
};
}]);
我在此代碼示例設置window.isPhoneGap早ondeviceready:navigator.connection.type not working even if device is ready *or* device is never ready