we use sliding menu in ONSEN UI & Navigator in it in order to show pages content. Now we want to prevent from closing app by pressing PHONE BACK KEY and instead it be redirected to the home page and if the users root was homepage,show an alert with this text "Do You Want To Close The App? {yes},{no}".
My index.html :
<ons-sliding-menu ng-if="!firstInit" menu-page="menu.html" side="right" main-page="home.html"
var="menu" type="push" swipe-target-width="150px" max-slide-distance="220px" swipeable="true">
</ons-sliding-menu>
My menu.html :
<ons-list-item modifier="tappable nodivider" ng-click="menu.setMainPage('home.html', {closeMenu: true})">
<p class="menu-text"><i class="fa fa-home fa-fw "></i>Home</p>
</ons-list-item>
<ons-list-item modifier="tappable nodivider" ng-click="menu.setMainPage('bill.html', {closeMenu: true})">
<p class="menu-text"><i class="fa fa-barcode fa-fw "></i>Enter Code</p>
</ons-list-item>
<ons-list-item modifier="tappable nodivider" ng-click="menu.setMainPage('account.html', {closeMenu: true})">
<p class="menu-text"><i class="fa fa-user fa-fw "></i>Login</p>
</ons-list-item>
<ons-list-item modifier="tappable nodivider" ng-click="menu.setMainPage('location.html', {closeMenu: true})">
<p class="menu-text"><i class="fa fa-map-o fa-fw "></i>Show On Map</p>
</ons-list-item>
My home.html :
<ons-navigator var="myNavigator" animation="none">
<ons-page ons-init="menu.setSwipeable(true)" on-device-backbutton="alert('Test!!!')">
.
.
.
<div class="box" ng-click="myNavigator.pushPage('cafe-details.html', {data: {cafeID: cafeItem.ID}})">
<div class="ribbon">
<span ng-show="cafeItem.IsSpecial">Offer</span>
</div>
<p>{{cafeItem.Name}}<br>
<i class="fa fa-map-marker fa-1x"></i>{{cafeItem.Address_Title}}</p>
<img class="img-responsive" ng-src="{{CafeImageURL}}{{cafeItem.Image[0].Image}}" loading-src="/images/cafe-no.jpg" fallback-src="/images/cafe-no.jpg" />
<span class="caption full-caption">
<i class="fa fa-eye"><a class="number"> {{cafeItem.Views}} </a></i>
<i class="fa fa-comments-o"><a class="number"> {{cafeItem.Comments}} </a></i>
<i class="fa fa-thumbs-o-up" id="likes"><a class="number"> {{cafeItem.Likes}} </a></i>
<i class="fa fa-thumbs-o-down" id="dislikes"><a class="number"> {{cafeItem.Dislikes}} </a></i>
</span>
</div>
Finally I found the solution
Just add this into index.js !
var back = 0;
document.addEventListener("backbutton",onBackButtonPressed, false);
function onBackButtonPressed(){
back++;
//alert(back);
if(back > 1){
$cordovaDialogs.confirm('Exit??', '', ['Yes','No'])
.then(function(buttonIndex) {
if(buttonIndex==1){
navigator.app.exitApp();
}
});
}
$timeout(function(){back=0;},2000);
var scope = angular.element(document.querySelector("ons-sliding-menu")).scope();
if(scope.menu.isMenuOpened()){
scope.menu.closeMenu('home.html');
} else{
scope.menu.setMainPage('home.html');
}
//
e.preventDefault();
}