Change back button (android) behaviour when Popup is active, ionic - angularjs

I'm trying to achieve this:
Scenario 1
User press back.
Popup appears asking if the user want to exit *
User press back.
App exits*
and
Scenario 2
User press back.
Popup appears asking if the user want to exit *
User press cancel
Popup closes
User press back.
Popup appears asking if the user want to exit *
User press back
App exits.
I tried using registerBackButtonAction and onHardwareBackButtoncombination but I can not get the exit popup to shows the second time (second scenario), it just exit.
This is the code I have now:
var exitPopupControl = function(event) {
//if I press back again, just go out
$ionicPlatform.onHardwareBackButton(function(event2){
navigator.app.exitApp();
});
if($state.current.name === "app.startseite"){
$ionicPopup.confirm({
title: 'Exit',
template: 'Do you want to exit? <br /><small>Press Back again to exit.</small>'
}).then(function(res) {
if(res) {
navigator.app.exitApp();
$rootScope.exitPopupShowed = false;
} else {
console.log('I choose not to left the app');
$ionicPlatform.registerBackButtonAction(exitPopupControl, 100);
}
});
}
else {
window.history.back();
}
};
$ionicPlatform.registerBackButtonAction(exitPopupControl, 100);

i did handel with following wa - just change confirmation popup code,
var exitPopupControl = function(event) {
//if I press back again, just go out
$ionicPlatform.onHardwareBackButton(function(event2){
navigator.app.exitApp();
});
if($state.current.name === "app.startseite"){
$ionicPopup.confirm({
title: 'Exit',
template: 'Do you want to exit? <br /><small>Press Back again to exit.</small>'
}).then(function(res) {
if(res) {
$rootScope.exitPopupShowed = false;
navigator.app.exitApp();
} else {
return;
}
});
}
else {
window.history.back();
}
};
$ionicPlatform.registerBackButtonAction(exitPopupControl, 100);
OR you can try something following:
document.addEventListener("deviceready", function() {
document.addEventListener("backbutton", function(e) {
$ionicPopup.confirm({
title: 'Exit',
template: 'Do you want to exit? <br /><small>Press Back again to exit.</small>'
}).then(function(res) {
if(res) {
$rootScope.exitPopupShowed = false;
navigator.app.exitApp();
} else {
return;
}
});
}, false);
}, false);
OR you can try something with toast, i prefer to use this one,
var countTimerForCloseApp = false;
$ionicPlatform.registerBackButtonAction(function(e) {
e.preventDefault();
function showConfirm() {
if (countTimerForCloseApp) {
ionic.Platform.exitApp();
} else {
countTimerForCloseApp = true;
showToastMsg($cordovaToast, 'Press again to exit.');
$timeout(function() {
countTimerForCloseApp = false;
}, 2000);
}
};
// Is there a page to go back to?
if ($ionicHistory.backView()) {
// Go back in history
$ionicHistory.backView().go();
} else {
// This is the last page: Show confirmation popup
showConfirm();
}
return false;
}, 101);
Thank you

Related

Execute an Angular function only if the current tab is active in the browser

I have an angular js function which should be called for every 2 seconds only when the current tab is open in the browser. Is there any way to check whether the current page is active in the browser.
$scope.callAtInterval = function() {
var url = "http://127.0.0.1/test";
$http.get(url).success( function(response) {
$scope.initial = response;
},
function errorCallback(response) {
$scope.result=response;
});
}
$interval( function(){ $scope.callAtInterval(); }, 5000);
}
I think below piece of code is self-explanatory
import { HostListener} from "#angular/core";
#HostListener("window:visibilitychange", ["$event"])
onVisibilityChange($event) {
const isVisible = $event.target.visibilityState === 'visible';
this.logger.info(isVisible);
if (isVisible) {
// tab is visible
} else {
// tab is not-visible
}
}
You would use the focus and blur events of the window:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// cancel your interval function
break;
case "focus":
// emit your interval function
break;
}
}
$(this).data("prevType", e.type);
})

how to check internet connection on button tap in ionic?

i'm trying to check for an internet connection once the login button is tapped but so far when the button is tapped, the app doesnt go through the next page but it also doesnt display the alert box. how to do it in ionic/angularjs? here's my code:
if (navigator.onLine) {
userFactory.getUser(usern).then(function(response)
{
if(JSON.stringify(response.data) === "null")
{
alert('Please sign-up for an account.');
}
else
{
if(pass === response.data.Password)
{
var myPopup = $ionicPopup.show({
template: '<input type="password" ng-model="userdata.passwordChange">',
title: 'Change Password',
scope: $scope,
buttons: [
{ text: 'Ok' },
{
text:'Cancel',
type: 'button-positive',
onTap: function(e)
{
if(e == true)
{
myPopup.close();
}
else
{
$location.path('/page17');
console.log($location.path());
myPopup.close();
}
}
}
]
});
}
else
{
if(pass == $scope.userdata.passwordChange)
{
$location.path('/page9');
}
else if(pass == "omar_1992!")
{
$location.path('/page9');
}
else
{
alert('Login failed. Please check your credentials.');
}
}
}
});
}else{
alert('no internet connection');
}
Create a factory that would handle all connectivity issue. Install cordova netwrok plugin to get more data like GPS, WiFi, to handle device and browser connectivity separately
cordova plugin add cordova-plugin-network-information
Include this factory in your controller and call ConnectivityMonitor.isOnline() to check if the user is connected to internet.
or Use ConnectivityMonitor.startWatching() to monitor the connectivity
app.factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){
var noInternetPopUp;
return {
isOnline: function(){
if(ionic.Platform.isWebView()){
return $cordovaNetwork.isOnline();
} else {
return navigator.onLine;
}
},
ifOffline: function(){
if(ionic.Platform.isWebView()){
return !$cordovaNetwork.isOnline();
} else {
return !navigator.onLine;
}
},
startWatching: function(){
if(ionic.Platform.isWebView()){
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
alert('Network Change : Online');
});
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
alert('Network Change : Offline');
});
}
else {
window.addEventListener("online", function(e) {
alert('Network Change : Online');
}, false);
window.addEventListener("offline", function(e) {
alert('Network Change : Offline');
}, false);
}
}
}
})
Use the below function
$scope.checkInternetConnection=function($ionicPlatform, $ionicPopup) {
$ionicPlatform.ready(function() {
if(window.Connection) {
if(navigator.connection.type == Connection.NONE) {
$ionicPopup.confirm({
title: "Internet Disconnected",
content: "The internet is disconnected on your device."
})
.then(function(result) {
if(!result) {
ionic.Platform.exitApp();
}
});
}
}
});

Ionic close IonicPopup when button makes an Ajax call

Am new to both angular and ionic. I have a popup in my page where i show user a input field to enter the OTP and a submit button. When i click on the submit button, I make an Ajax call to check if the OTP is valid.
But am not able to close the popup with .close method. Please help
var OTPPopup = $ionicPopup.show({
title: 'OTP VERIFICATION',
templateUrl: 'templates/login/otp.html',
scope: $scope,
buttons : [{
text: 'Confirm OTP',
type: 'button-assertive',
onTap : function(e) {
e.preventDefault();
var validateResponse = validateOTP();
validateResponse.then(function(response){
console.log('success', response);
return response;
});
}
}]
}).then(function(result){
console.log('Tapped', result);
OTPPopup.close();
});
And below is the function validateOTP
function validateOTP() {
var requestObj = {
authentication: {
email_id: $scope.loginForm.email,
security_code: $scope.OTP
}
};
return $q(function(resolve, reject) {
activateUser(requestObj, function(response){
if(response.error == null && response.data.isSuccess) {
console.log('validate correct');
resolve(response);
}
}, function(response){
return 'error';
});
});
}
activateUser is my service which makes the ajax call. Please let me know how can i acheive this.
console.log('success', response) is being printed inside the .then but after returning something from the onTap , the promise of the popup is not being called.
Ended up solving it myself.
This solution would work only if you have exactly one ionicPopup on your page. I just wrote this line of code to do the trick
$ionicPopup._popupStack[0].responseDeferred.resolve();
This automatically closes the popup. The whole code is more simpler now with normal Ajax without any q promises.
var OTPPopup = $ionicPopup.show({
title: 'OTP VERIFICATION',
templateUrl: 'templates/login/otp.html',
scope: $scope,
buttons : [{
text: 'Confirm OTP',
type: 'button-assertive',
onTap : function(e) {
// e.preventDefault() will stop the popup from closing when tapped.
e.preventDefault();
validateOTP();
}
}]
});
and in the next function
function validateOTP() {
var requestObj = {
authentication: {
email_id: $scope.loginForm.email,
security_code: $scope.loginForm.OTP
}
};
activateUser(requestObj, function(response){
if(response.error == null && response.data.isSuccess) {
localStorage.setLocalstorage = response.data.user[0];
$ionicPopup._popupStack[0].responseDeferred.resolve();
$state.go('dashboard.classified');
}
}, function(response){
});
}
you don't need call e.preventDefault();
you just only return the validateOTP promise
ionicPopup will waiting the promise then close popup
var OTPPopup = $ionicPopup.show({
title: 'OTP VERIFICATION',
template: 'templates/login/otp.html',
scope: $scope,
buttons : [{
text: 'Confirm OTP',
type: 'button-assertive',
onTap : function() {
return validateOTP();
}
}]
}).then(function(result){
console.log('closed', result); // result is the activateUser resolve response
});

disable'$scope.$on('$locationChangeStart' )' if user click cancel?

I have problem when the user click cancel and it is true it will redirtect i it will trigger $scope.$on('$locationChangeStart') becouse of that I will have 'You have unsaved changes. If you continue your changes will be lost.' appear twice. just want to ask how can I disable'$scope.$on('$locationChangeStart' )' if user click cancel
code
$scope.cancel = function() {
var validator = npFormValidator($scope);
if ($scope.npForm.$dirty) {
var answer = confirm('You have unsaved changes. If you continue your changes will be lost.');
if (answer) {
$location.path('/home');
} else {
validator.addWatches();
event.preventDefault();
}
}
};
$scope.$on('$locationChangeStart', function (event) {
var validator = npFormValidator($scope);
if (validator.valid() && $scope.model.clickedSave) {
window.onbeforeunload = undefined;
} else {
if ($scope.npForm.$dirty) {
var answer = confirm('You have unsaved changes. If you continue your changes will be lost.');
if (!answer) {
validator.addWatches();
event.preventDefault();
}
}
}
})
;
You can set a flag and check it in your event receiver:
var canceled = false;
$scope.cancel = function() {
var validator = npFormValidator($scope);
if ($scope.npForm.$dirty) {
var answer = confirm('You have unsaved changes. If you continue your changes will be lost.');
if (answer) {
canceled = true;
$location.path('/home');
} else {
canceled = false;
validator.addWatches();
event.preventDefault();
}
}
};
$scope.$on('$locationChangeStart', function (event) {
if (canceled) return;
var validator = npFormValidator($scope);
if (validator.valid() && $scope.model.clickedSave) {
window.onbeforeunload = undefined;
} else {
if ($scope.npForm.$dirty) {
var answer = confirm('You have unsaved changes. If you continue your changes will be lost.');
if (!answer) {
validator.addWatches();
event.preventDefault();
}
}
}
});

Clear form after submit and disable form in angular service

I create a service to upload content.
it takes 4 argument
which folder to update
the content
set the form to disabled
clear form after submit
create: function(folderID, text, o, master) {
o.isDisabled = true;
ob = {
text: text,
media: 'Pending',
createdBy: $rootScope.AUTH.user.uid,
createdTime: Firebase.ServerValue.TIMESTAMP
};
_firebaseRef.files.child(folderID).push(ob, function(error) { $timeout(function() {
if (error) {
alert('Create file failed, please try again'); o.isDisabled = false;
} else {
o.isDisabled = false;
angular.copy(master, o);
};
});
});
},
So when in controller.
service.create(folderID, 'hello world', $scope.file, $scope.master);
My question
How can I omit the 3rd and 4th arguments?

Resources