要绑定到物理后退按钮,您可以使用:
document.addEventListener("backbutton", $scope.goBack, false);
为此,您需要在控制器中使用 Angular $window 和 $location 服务的组合。我建议不要覆盖您的 $parent 范围函数,因为您可能会在另一个页面上出现奇怪的行为。另外,请注意您不允许在 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 即使设备已准备好 *或* 设备从未准备好