Ionic - Email/Password required - angularjs

I have authentication for my login when wrong email format, email or password, it will show a pop up error. However if nothing is type in both email and password, it will stuck at loading page. Anybody has a solution?
login.html
<ion-view title="Login" hide-nav-bar="true" hide-back-button="true" id="page6">
<ion-content padding="true" style="background: url(img/fOM24l77SrSIyzBwqvMz_login.jpg) no-repeat center;background-size:cover;" class="manual-ios-statusbar-padding">
<div class="spacer" style="width: 300px; height: 82px;"></div>
<h4 style="color: #FFFFFF;" align="center">Login with your NYP SIT account</h4>
<form name="loginForm" class="list " id="login-form1">
<ion-list class=" " id="login-list2">
<div class="app-icon"></div>
<label class="item item-input item-floating-label">
<span class="input-label" style="color: #9F9F9F;">Email</span>
<input ng-model="user.email" style="color: white;" type="email" placeholder="Email">
</label>
<label class="item item-input item-floating-label">
<span class="input-label" style="color: #9F9F9F;" >Password</span>
<input ng-model="user.password" style="color: white;" type="password" placeholder="Password">
</label>
</ion-list>
<div style="height: 40px;" class="spacer"></div>
<button ng-click="loginEmail(loginForm,user)" class=" button button-assertive button-block icon-left ion-ios-email-outline " id="signup-button3">LOGIN WITH EMAIL</button>
</form>
</ion-content>
</ion-view>
controller.js
.controller('loginCtrl', function($scope, $rootScope, $ionicHistory, sharedUtils, $state, $ionicSideMenuDelegate) {
$rootScope.extras = false; // For hiding the side bar and nav icon
// When the user logs out and reaches login page,
// we clear all the history and cache to prevent back link
$scope.$on('$ionicView.enter', function(ev) {
if(ev.targetScope !== $scope){
$ionicHistory.clearHistory();
$ionicHistory.clearCache();
}
});
//Check if user already logged in
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
//Removes back link to login page
$ionicHistory.nextViewOptions({
historyRoot: true
});
$ionicSideMenuDelegate.canDragContent(true); // Sets up the sideMenu dragable
$rootScope.extras = true;
sharedUtils.hideLoading();
$state.go('tabs.home', {}, {location: "replace"});
}
});
$scope.loginEmail = function(formName,cred) {
if(formName.$valid) { // Check if the form data is valid or not
sharedUtils.showLoading(); //starts the loading popup
//Email Login via Firebase
firebase.auth().signInWithEmailAndPassword(cred.email,cred.password).then(function(result) {
// You dont need to save the users session in your local session or cookies. Firebase handles it.
// You only need to :
// 1. clear the login page history from the history stack so that you cant come back
// 2. Set rootScope.extra;
// 3. Turn off the loading
// 4. Got to menu page
$ionicHistory.nextViewOptions({
historyRoot: true //1
});
$rootScope.extras = true; //2
sharedUtils.hideLoading(); //3
$state.go('tabs.home', {}, {location: "replace"}); //4
},
function(error) {
sharedUtils.hideLoading();
sharedUtils.showAlert("ERROR!","Authentication Error");
}
);
}else{
sharedUtils.showAlert("ERROR!","Enter in email format");
}
};
})

i think its better to check if the field is empty or not if fields are empty then you can show an error message
$scope.loginEmail = function(formName, cred) {
if (formName && cred) { //checking for null
if (formName.$valid) { // Check if the form data is valid or not
sharedUtils.showLoading(); //starts the loading popup
//Email Login via Firebase
firebase.auth().signInWithEmailAndPassword(cred.email, cred.password).then(function(result) {
$ionicHistory.nextViewOptions({
historyRoot: true //1
});
$rootScope.extras = true; //2
sharedUtils.hideLoading(); //3
$state.go('tabs.home', {}, {
location: "replace"
}); //4
},
function(error) {
sharedUtils.hideLoading();
sharedUtils.showAlert("ERROR!", "Authentication Error");
}
);
} else {
sharedUtils.showAlert("ERROR!", "Enter in email format");
}
} else {
sharedUtils.showAlert("ERROR!", "Fields cannot be empty");
}
};

Related

How can I use ng-if with ionicPopup

I'm trying to do so, when I click on the send button a popup appears, where if the person enters the correct message it goes to the next screen if not it stays on the screen that is.
my code :
my controller.js
.controller('loginController', function($scope, $stateParams, $ionicPopup, $ionicHistory, $state) {
$scope.Enviar = function(){
var confirmPopup = $ionicPopup.prompt({
title: 'Login',
template: 'Pergunta: Digite a P∴S∴ do AP∴?',
inputType: 'text',
inputPlaceholder: 'Digite a senha',
ng-model="login"
});
confirmPopup.then(function(res) {
if(res) {
$state.go('app.home');
} else {
console.log('teste');
$state.go('login');
}
})
}
})
my login.html
<ion-view view-title="login">
<ion-content class="login-principal" scroll="true">
<div class="login-imagem">
<img class="full-image" ng-src="img/GOMB.jpg">
</div>
<div>
<ion-list class="list-inset">
<ion-item class="item-input">
<i class="icon ion-ios-email-outline placeholder-icon"></i>
<input type="text" placeholder="E-mail">
</ion-item>
<ion-item class="item-input">
<i class="icon ion-ios-locked-outline placeholder-icon"></i>
<input type="text" placeholder="Senha">
</ion-item>
</ion-list>
<div class="row login">
<div class = "col col-50" >
<a class="button button-block button-dark" ui-sref="app.cadastroUsuario">Criar conta</a>
</div>
<div class = "col col-50" >
<a class="button button-block button-dark" ng-click="Enviar()">Entrar</a>
</div>
</div>
</div>
</ion-content>
</ion-view>
My question is how to use ng-model and ng-if with ionicPopup?
Instead of $ionicPopup.prompt you can just make use of $ionicPopup.show and in template property of its object write whatever the template you want (with ng-model & ng-if). You can also have buttons with their customizable text as well as particular action onTap (like returning model value of input fields inside popup). So, you can have following function to call popup:
$scope.showPopup = function() {
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<input type="password" ng-if="isNotConnected"
ng-model="data.wifi" placeholder="Enter Password">',
title: 'Enter Wi-Fi Password',
subTitle: 'Please use normal things',
scope: $scope,
buttons: [
{ text: 'Cancel' },
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function(e) {
if (!$scope.data.wifi) {
//don't allow the user to close unless he enters wifi password
e.preventDefault();
} else {
return $scope.data.wifi;
}
}
},
]
});
myPopup.then(function(res) {
console.log('Tapped!', res);
});
};
Check out this codepen: https://codepen.io/anon/pen/wqwzPE
$scope.Enviar = function(){
var obj = new String("boa");
$ionicHistory.nextViewOptions({
disableBack : true
})
var confirmPopup = $ionicPopup.prompt({
title: 'Login',
template: 'Pergunta: Digite a?',
inputType: 'text',
inputPlaceholder: 'Digite em minusculo'
});
confirmPopup.then(function(res) {
if(res == obj) {
$state.go('app.home');
console.log(res);
} else {
//console.log('teste');
$state.go('login');
//console.log(res);
}
})
}

Angularjs multiple functions

I have 2 buttons:
One scans a QR code and returns the values which works.
Another on the same page that confirms the input values, but I cannot get the second function to fire.
I have 2 inputs, deviceid and companyid, and 2 buttons. The scan button, via ng-click, calls scanQR and the second button, also via ng-click, calls checkBlanks.
A confirm ID button calls a functions to firstly check for blanks then alert the user if the input data is missing. Once the 2 inputs have content it will save the data via the verifyDetails() call. But I cannot get the checkBlanks function to run.
HTML Code is:-
<ion-view title="Settings">
<ion-content padding="true" class="has-header">
<form class="list">
<label class="item item-input" name="deviceid">
<span class="input-label">Device ID</span>
<input type="text" placeholder="" ng-model="deviceid">
</label>
<label class="item item-input" name="companyid">
<span class="input-label">Company ID</span>
<input type="text" placeholder="" ng-model="companyid">
</label>
</form>
<button ng-click="scanQR()" class="button button-positive button-block">Scan QR to Configure</button>
<button ng-click="checkBlanks()" class="button button-positive button-block">Confirm ID</button>
<form class="list">
<ion-toggle toggle-class="toggle-positive" ng-checked="true">Vibrate</ion-toggle>
<ion-toggle toggle-class="toggle-positive">Light on Scan</ion-toggle>
<div style="text-align:center;" class="show-list-numbers-and-dots">
<p style="color:#000000;font-size:10px;">On Android devices set to off and use the volume controls to turn the flashlight on or off.</p>
</div>
<ion-radio ng-model="radioCheck" value="security">Security</ion-radio>
<ion-radio value="utilities">Utilities</ion-radio>
</form>
</ion-content>
</ion-view>
AngularJS is:-
function($scope, $stateParams) {
$scope.radioCheck = "security";
$scope.scanQR = function() {
cordova.plugins.barcodeScanner.scan(
function(result) {
var TagResponse = result.text;
var config = TagResponse.indexOf("Config:");
if (TagResponse !== '') {
if (config === 0) {
var ConfigVals = TagResponse.split(':');
$scope.deviceid = ConfigVals[1];
$scope.companyid = ConfigVals[2];
$scope.$apply();
}
}
});
};
$scope.checkBlanks = function() {
alert("Device ID" + $scope.deviceid);
console.log("Device ID" + $scope.device)
if ($scope.deviceid === '') {
alert("Please enter a device ID", Dismissed, "Error");
} else if ($scope.companyid === '') {
alert("Please enter a Company ID", Dismissed, "Error");
} else {
verifyDetails();
}
};
}
Any help appreciated, I'm very new to Angularjs and Ionic.

angular js: Unable to validate a textarea

fellas!
I'm trying to validate a text area upon clicking a link. Thing is, It's not coming inside a form. And when a user clicks a link, content entered in the text area should be posted (saved to database).
I wrote a validation for that. And unfortunately, it's not working and I'm able to make blank posts. I'm trying to prevent blank post posting. I have recreated the form and the controller in a fiddle. Link I'll provide down. but before that, take a look at my html and js code.
HTML
<div ng-app="myApp" ng-controller="myMap">
<div class="post-textarea" ng-class="{ 'has-error': vm.currentPost.content.$dirty && vm.currentPost.content.$error.required }">
<textarea class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
<a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
</div>
</div>
JavaScript
angular.module('myApp', [])
.factory('myService', function($http) {
var baseUrl = 'api/';
return {
postCurrentPost: function(newPost) {
var dataPost = {
newPost: newPost
};
return $http({
method: 'post',
url: baseUrl + 'postCurrentPost',
data: dataPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
};
})
.controller('myMap', function(myService, $http, $scope) {
var vm = this;
var userObject;
// Add a post
vm.addPost = function(newPost, isValid) {
if (isValid) {
var currentPost = vm.currentPost;
currentPost.content = ""; //clear post textarea
myService.postCurrentPost(newPost).success(function(data) {
vm.posts = data;
});
} else {
alert('Validation not working');
}
};
//Check validation
$scope.getError = function(error, name) {
if (angular.isDefined(error)) {
if (error.required && name == 'vm.currentPost.content') {
return "This field is required";
}
}
}
});
And here's a FIDDLE.
Name of the form input element should be used instead of model value.
https://docs.angularjs.org/api/ng/directive/form
<div ng-app="myApp" ng-controller="myMap">
<form name="formContent">
<div class="post-textarea" ng-class="{ 'has-error': formContent.content.$dirty && formContent.content.$error.required }">
<textarea name='content' class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
<a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
</div>
</form>
Content is dirty: {{formContent.content.$dirty}}
<br>
Content has required: {{formContent.content.$error.required}}
</div>

How to clear form after post?

I'm creating an app using Ionic. After send values of form I want to clear form but I can't do this.
How could I do this ?
form
<form name="Empresa">
<div class="list">
<label class="item item-input"
ng-class="{'has-errors':Empresa.nomeemp.$invalid, 'no-errors':Empresa.nomeemp.$valid}">
<input type="text"
placeholder="Nome"
name="nomeemp"
ng-model="Empresa.nome"
ng-required="true">
</label>
<div class="error-container"
ng-show="(Empresa.nomeemp.$dirty || !Empresa.nomeemp.$pristine)"
ng-messages="Empresa.nomeemp.$error">
<div ng-messages-include="templates/form-errors.html"></div>
</div>
</div>
<button type="button" class="button button-block button-energized"
ng-disabled="Empresa.$invalid" ng-click="addEmpresa(Empresa);">Cadastrar</button>
</form>
controller
$scope.addEmpresa = function(Empresa){
var _pathFile = document.getElementById("smallimage").src;
var _fileName = _pathFile.substr(_pathFile.lastIndexOf('/') + 1);
if(_fileName === 'no-image.png'){
$ionicLoading.show({ template: APP_MESSAGES.escolhaImagem, noBackdrop: true, duration: 2000 });
}else{
$ionicLoading.show();
EmpresaAPIService.addEmpresa(Empresa).then(function (data) {
$ionicLoading.hide();
var retorno = JSON.parse(data.response);
if(retorno.status === 0){
$ionicLoading.show({ template: retorno.msg, noBackdrop: true, duration: 2000 });
}
if(retorno.status === 1){
//clear form
delete Empresa;
Empresa.$setPristine();
Empresa.$setUntouched();
$ionicLoading.show({ template: retorno.msg, noBackdrop: true, duration: 2000 });
}
}, function (err) {
$ionicLoading.hide();
}, function (progress) {
// PROGRESS HANDLING GOES HERE
});
}
}
In your controller after you do your submission logic, set $scope.Empresa.noma = ''; as that's what is being bound to your form in your application.
edit: setPristine() should also work.

Authentication when using AngularJS, Express.js and PassportJS

I have AngularJS for front - Node.js(Express.js) for sever side web application and having trouble getting the authentication.
this is login page URL.
http://localhost:3000/#/extra-signin
After I filled email and password, and pushed login button. but still same page displayed.
URL after pushed login button is just like below.
http://localhost:3000/?email=test%40test.com&password=test#/extra-signin
I expected Angular controller would help posting login data to server by post method, but Angular controller seems not working. It seems get method working.
Angular controller:
App.controller('ExtraSigninController', function($scope, $routeParams, $http, $location, $rootScope, $alert, $window) {
$scope.login = function() {
$http.post('/auth/login',$scope.user)
.success(function(data) {
$window.localStorage.token = data.token;
var payload = JSON.parse($window.atob(data.token.split('.')[1]));
$rootScope.currentUser = payload.user;
$location.path('/');
$alert({
title: 'Cheers!',
content: 'You have successfully logged in.',
animation: 'fadeZoomFadeDown',
type: 'material',
duration: 3
});
})
.error(function() {
delete $window.localStorage.token;
$alert({
title: 'Error!',
content: 'Invalid username or password.',
animation: 'fadeZoomFadeDown',
type: 'material',
duration: 3
});
});
}
}
Angular config:
App.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/extra-signup', {
templateUrl: 'templates/states/extra-signup.html',
controller: 'ExtraSignupController'
})
.when ....
.when ....
.otherwise({
redirectTo: '/'
});
});
HTML login page:
<div id="signin-page">
<div class="page-form-wrapper"></div>
<div class="page-form">
<div class="header-content">
<h1>login</h1>
</div>
<div class="body-content">
<p>login:</p>
<div class="row mbm text-center">
<div class="col-md-4"><i class="fa fa-twitter fa-fw"></i>Twitter</div>
<div class="col-md-4"><i class="fa fa-facebook fa-fw"></i>Facebook</div>
<div class="col-md-4"><i class="fa fa-google-plus fa-fw"></i>Google +</div>
</div>
<form class="form">
<div class="form-group">
<div class="input-icon right"><i class="fa fa-user"></i>
<input type="text" placeholder="Email" name="email" ng-model="user.email" class="form-control input-lg" required autofocus/>
</div>
</div>
<div class="form-group">
<div class="input-icon right"><i class="fa fa-key"></i>
<input type="password" placeholder="password" name="password" mg-model="user.password" class="form-control input-lg" required/>
</div>
</div>
<div class="form-group pull-right">
<input type="submit" class="btn btn-success" ng-click="login()" value="login">
</div>
</form>
</div>
</div>
</div>
this is server side code:
app.post('/users/session', passport.authenticate('local'));
//passport local strategy
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
db.User.find({ where: { email: email }}).success(function(user) {
if (!user) {
// done(null, false, { message: 'Unknown user' });
res.send(401, 'User does not exist');
} else if (!user.authenticate(password)) {
// done(null, false, { message: 'Invalid password'});
res.send(401, 'Invalid email and/or password');
} else {
logger.debug('Login (local) : { id: ' + user.id + ', username: ' + user.username + ' }');
// done(null, user);
var token = createJwtToken(user);
res.send({ token: token });
}
}).error(function(err){
done(err);
});
}
));
I don't know why Angular Controller's post method doesn't work. and I don't understand why returned url is like that. Position of get parameter is something wrong.
Not sure what I am doing wrong?
Any advice would be great

Resources