Clear form after submit and disable form in angular service - angularjs

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?

Related

How to show a message when navigating from one page to another

On success message I want to navigate from uploaded page to customer page and highlight my alert as success , but my alert is not getting open. Need solution
Upload.js
if (status == 200){
$state.go('customer', {"id": $scope.customer});
$rootScope.$emit('custSucess');
}
customer.js
$rootScope.$on('custSucess',function(event){
$scope.message = {
content: [{
title: '',
msg:'hi'
}],
type: 'success'
};
});
So what I ended up doing is creating a service for handling my alerts. Here is the service code:
app.factory('AlertService', function () {
var success = {},
error = {},
alert = false;
return {
getSuccess: function () {
return success;
},
setSuccess: function (value) {
success = value;
alert = true;
},
getError: function () {
return error;
},
setError: function (value) {
error = value;
alert = true;
},
reset: function () {
success = {};
error = {};
alert = false;
},
hasAlert: function () {
return alert;
}
}
});
//And I simply set it when I need to like so:
AlertService.setSuccess({ show: true, msg: name + ' has been updated successfully.' });
//And check for it on the page that would display it like this:
if (AlertService.hasAlert()) {
$scope.success = AlertService.getSuccess();
AlertService.reset();
}`enter code here`

Cordova contact plugin not working

After calling this function I am getting the following error:
"TypeError: Cannot read property 'pickContact' of undefined"
$scope.pickContact = function() {
navigator.contacts.pickContact(function(contact) {
if(contact) {
$scope.requestData.guestName = contact.displayName;
if(contact.phoneNumbers && contact.phoneNumbers.length > 0) {
$scope.requestData.phoneNo = contact.phoneNumbers[0].value;
} else {
$scope.requestData.phoneNo = null;
}
$scope.$apply();
} else {
$ionicPopup.alert({
title: 'Error!',
template: 'Unable to get contact details'
});
}
}, function(err) {
console.log('Error: ' + err);
$ionicPopup.alert({
title: 'Error!',
template: 'Unable to get contact details'
});
});
};
Use the $cordovaContacts plugin for get contacts and inject the dependency in your controller.
This plugin is available only on devices, not in the browser please do test on device.
For this plugin first you need to install ngCordova, this will support you for many more plugins and implementations.
Install plugin using following command,
cordova plugin add cordova-plugin-contacts
Example :
.controller('MyCtrl', function($scope, $cordovaContacts, $ionicPlatform) {
$scope.addContact = function() {
$cordovaContacts.save($scope.contactForm).then(function(result) {
// Contact saved
}, function(err) {
// Contact error
});
};
$scope.getAllContacts = function() {
$cordovaContacts.find().then(function(allContacts) { //omitting parameter to .find() causes all contacts to be returned
$scope.contacts = allContacts;
}
};
$scope.findContactsBySearchTerm = function (searchTerm) {
var opts = { //search options
filter : searchTerm, // 'Bob'
multiple: true, // Yes, return any contact that matches criteria
fields: [ 'displayName', 'name' ] // These are the fields to search for 'bob'.
desiredFields: [id]; //return fields.
};
if ($ionicPlatform.isAndroid()) {
opts.hasPhoneNumber = true; //hasPhoneNumber only works for android.
};
$cordovaContacts.find(opts).then(function (contactsFound) {
$scope.contacts = contactsFound;
};
}
$scope.pickContactUsingNativeUI = function () {
$cordovaContacts.pickContact().then(function (contactPicked) {
$scope.contact = contactPicked;
}
}
});
Hope this will help you !!

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

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

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
});

Event loop Angular. Some functions not running on app initialisation until a button is clicked? -FIREBASE

Background:
I have the following setup to authenticate retrieve my user and then retrieve his credentials. I am unclear on the event loop even after reading the documentation.
The Question:
The user is not displayed until I click a button? Every other kind of function runs on initialization like the alerts and stuff but why is my retrieve user function working until another button is pressed (pressing any button )?
Summary:
In order to retrieve the username for some reason I need to click something. I want the username to be retrieve on initialization .
crossfitApp.controller('globalIdCtrl', ["$scope",'$q','defautProfileData','$timeout', function ($scope,$q,defautProfileData,$timeout) {
$timeout(function() {
var dataRef = new Firebase("https://glowing-fire-5401.firebaseIO.com");
$scope.myFbvar =null;
$scope.authenticated={
currentUser: null,
avatarUrl: "",
emailAddress: "",
settings: "",
currentUserid: null,
};
function getProfile(userID){
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
$scope.authenticated.currentUser = nameSnapshot.val();
});
};
$scope.auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
}
else if (user) {
//logged in
$scope.$apply(function(){getProfile(user.id);})
console.log('logged in');
$scope.authenticated.currentUserid = user.id ;//
}
else {
// user is logged out
console.log('logged out');
$scope.authenticated.currentUserid =null;
$scope.authenticated.currentUserid =null;
}
});
},100);
}]); //GlobaldCtrl
I would move most of your code to a service, and call the service from your controller, like this. I also included a deferred object in your login as I bet this is async
crossfittpApp.service('firebase',function($q) {
return {
getUser : function(authenticated) {
var dataRef = new Firebase("https://glowing-fire-5401.firebaseIO.com"),
myFbvar =null,
getProfile(userID) {
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
authenticated.currentUser = nameSnapshot.val();
});
},
deferredObj = $q.defer();
auth;
auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
deferObj.reject();
}
else if (user) {
//logged in
getProfile(user.id);
console.log('logged in');
authenticated.currentUserid = user.id ;
deferObj.resolve(auth);
}
else {
// user is logged out
console.log('logged out');
authenticated.currentUserid =null;
deferObj.resolve();
}
}
return deferObj.promise;
}
}
});
crossfittpApp.controller('globalIdCtrl',function(firebase) {
$scope.authenticated = {
currentUser: null,
avatarUrl: "",
emailAddress: "",
settings: "",
currentUserid: null,
};
firebase.getUser(authenticated)
.then(function(_auth) {
$scope.auth = _auth;
},
function() {
//auth error here
});
});
You're not triggering Angular's HTML Compiler, so Angular doesn't know you've changed the JS variables.
Whenever you use an event like ng-click/ng-submit/etc, Angular fires $scope.$apply(), which checks for any changes to your $scope variables and applies them to the DOM, which is why it shows up after this.
You can correct this issue by alerting Angular that it needs to run $apply by using $timeout:
angular.controller('MyController', function($timeout) {
myprofile= new Firebase("https://glowing-fire-5401.firebaseio.com/profiles/"+userID+"/username");
myprofile.once('value', function(nameSnapshot) {
$timeout(function() {
authenticated.currentUser = nameSnapshot.val();
});
});
auth = new FirebaseSimpleLogin(dataRef, function(error, user) {
if (error) {
//Error
console.log ('error');
}
else if (user) {
$timeout(function() {
authenticated.currentUserid = user.id ;
});
}
else {
$timeout(function(){
authenticated.currentUserid =null;
});
}
});
});
You should utilize angularFire, which abstracts these complexities.
There are some more questions like this one here, here, and here.

Resources