pass an object from controller to another controller angularjs - angularjs

after Signup, how to be automatically redirected to the authentificate page and put the login and the password in the form of authenficate.html ?
the signupCtrl
demoApp.controller('signupCtrl',function($scope,$http,$location,User) {
User=$scope.user;
$scope.verification = function(isValid,User) {
User=$scope.user;
if (isValid) {
$scope.message = "Submitted ";
console.log(User);
console.log(User.type);
if(User.type=="recruteur")
{
window.alert("bonjour recruteur "+ User.email);
$location.path("/auth");
}
else {
window.alert("bonjour condidat "+ User.email);
$location.path("/auth");
}
} else {
$scope.message = "There are still invalid fields below";
}
};
});
the SINGUP.html
<body ng-controller="signupCtrl">
<form name="registrationForm" novalidate
ng-submit="submit(registrationForm.$valid)">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-group"
ng-model="user.email"
required />
</div>
<div>
<label>Password</label>
<input type="password" name="password"
ng-model="user.password"
required/>
</div>
<div>
<button type="submit" ng-click="verification(registrationForm.$valid,registrationForm.user)">Register!</button>
</div>
</form>
</body>
controller authentificate:
demoApp.controller('personCtrl',function ($scope, $http,$location,User) {
console.log(User);
var person=User;
$scope.emaill=person.email;
$scope.pwd=person.password;
console.log(person);
});
authentificate page:
<body>
<form>
<input type="text" ng-model="emaill">
<input type="password" ng-model="pwd">
<input type="submit" value="Connexion" ng-click="connexion(person)">
</form>
</body>
the route provider
demoApp.config(['$routeProvider',
function($routeProvider){
//systeme de routage
console.log('rederction');
$routeProvider.when ('/auth',{templateUrl: 'authentficate.html',
controller: 'personCtrl'})
.otherwise({redirectTo: 'Signup.html'}
);
}
]);

You can put the data that is needed for the session in a Service.
https://docs.angularjs.org/guide/services
But dont put the Password there, only the Username and an Authentication token.
Check here for a complete sample for an token based authentication
https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

Related

not able to access form contents such as username... in my controller AngularjS

I am trying to implement registration functionality where in the user details from the form will be saved to the database. To do that I am trying to access username in my controller and it gives undefined.
username is:undefined signup.controller.js (13,9)
(function() {
var app = angular.module("myApp");
app.controller("registerController", function(registrationService) {
var self = this;
self.registrationFormSubmission = function() {
// $rootScope.id=1;
var usern = self.username;
console.log("username is:" + self.form.username);
self.user = {};
self.user = {
id: 1,
username: self.username,
firstname: self.firstname,
lastname: self.lastname,
email: self.email,
password: ""
};
return self.user;
registrationService
.saveUserInfo(user)
.then(function() {
self.suceess = "user registered successfully";
console.log("form submission successful");
window.alert("form submission successful");
})
.then(function() {
self.failure = "Error occurred while registering user!";
});
};
});
})();
<form name="registerctrl.form" role="form">
<div class="container-fluid">
<h4>Register</h4>
<p>Please fill in this form to create an account.</p>
<hr>
<div class="form-group" ng-class="{'has-error':form.username.$dirty && form.username.$error.required}">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter username" ng-modal="registerctrl.username" name="username" required>
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
{{form.username}}
</div>
<div class="form-group" ng-class="{'has-error':form.firstname.$dirty && form.firstname.$error.required}">
<label for="firstname">Firstname:</label>
<input type="text" class="form-control" id="firstname" placeholder="Enter firstname" ng-modal="registerctrl.firstname" name="firstname" required>
<span ng-show="form.firstname.$dirty && form.firstname.$error.required" class="help-block">Firstname is required</span>
<hr>
<p>By creating an account you agree to our Terms & Privacy.</p>
<button class="button" ng-click="registerctrl.registrationFormSubmission()">Register</button>
<p>Already have an account? Sign in.</p>
</div>
</div>
</form>
Seems like the problem is in typo.
You have
ng-modal="registerctrl.username"
Should be
ng-model="registerctrl.username"

angular dropdown option value login data object for user roles in database

So I am finding myself at a bit of a roadblock on taking grabbing a value from a dropdown option in angular for creating one of two specific user roles for my postgreSQL database.
I have many inputs (several exclusive to each dropdown) for creating users such as:
1. username
2. password
3. email
etc...
all are easily passed into a user object within my angular controller using ng-model to reference them. What I am trying to achieve with my form is for each option of my select dropdown to log a specific value to the key of role within my user object so i can store that to a specific record within the field of 'role'.
HTML Snippit:
<form name="createAccount" ng-submit="create(this)">
<select ng-model="showRole" class="form-control" ng-options="role.abbreviation as role.name for role in roles">
<option value="">Choose One</option>
</select>
<div ng-switch="showRole">
<div ng-switch-when="agt">
<div>
<label for="firstName">First Name</label>
<input type="text" ng-model="createAccount.firstName">
</div>
<div>
<label for="lastName">Last Name</label>
<input type="text" ng-model="createAccount.lastName">
</div>
<div>
<label for="email">E-mail</label>
<input type="e-mail" ng-model="createAccount.email">
</div>
<div>
<label for="company">Agency</label>
<input type="text" ng-model="createAccount.company">
</div>
<div>
<label for="createAccount-username">Username</label>
<input type="text" ng-model="createAccount.username">
</div>
<div>
<label for="createAccount-password">Password</label>
<input type="password" ng-model="createAccount.password">
</div>
<div>
<label for="createAccount-passwordConfirm">Password Confirm</label>
<input type="password" ng-model="createAccount.passwordConfirm">
</div>
</div>
<div ng-switch-when="pmt">
<div>
<label for="firstName">First Name</label>
<input type="text" ng-model="createAccount.firstName">
</div>
<div>
<label for="lastName">Last Name</label>
<input type="text" ng-model="createAccount.lastName">
</div>
<div>
<label for="email">E-mail</label>
<input type="e-mail" ng-model="createAccount.email">
</div>
<div>
<label for="company">Venue</label>
<input type="text" ng-model="createAccount.company">
</div>
<div>
<label for="createAccount-username">Username</label>
<input type="text" ng-model="createAccount.username">
</div>
<div>
<label for="createAccount-password">Password</label>
<input type="password" ng-model="createAccount.password">
</div>
<div>
<label for="createAccount-passwordConfirm">Password Confirm</label>
<input type="password" ng-model="createAccount.passwordConfirm">
</div>
</div>
<div>
<button>Create Account</button>
</div>
and Angular Controller:
(function(){
var LoginController = function ($scope, $http ) {
$scope.pageID = "Login/Register Page";
$scope.create = (form) => {
console.log('create form submitted');
const user = {
firstName: form.createAccount.firstName,
lastName: form.createAccount.lastName,
email: form.createAccount.email,
company: form.createAccount.company,
username: form.createAccount.username,
password: form.createAccount.password,
}
$http.post('/users/create', user)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
}
$scope.loginSubmitted = (form) => {
console.log('login form submitted');
}
$scope.roles = [{ abbreviation: 'agt', name: "Agent"},{abbreviation: 'pmt', name: "Promoter"}];
this.setTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
this.notSelected = function(checkTab) {
return !(this.isSelected(checkTab));
};
this.getTab = function() {
return this.tab;
};
this.setIsDefault = function() {
this.isDefault = true;
};
this.getIsDefault = function() {
return this.isDefault;
};
}
angular.module('avp')
.controller('LoginController', LoginController);
LoginController.$inject = ['$scope', '$http'];
}())
OK. I am kinda ashamed of the fact that I asked such a dumb question but it is event more satisfying to figure out the answer and answer my own question on here for the first time.
All I had to do was new property in user object with form.showRole. WHOOO Crazy!
Overthinking it FTW!

Angular form submissions issues

This is my signup.html file i want to take only password and username from this form to my controller.but I not able to access form elements through this !
<ion-view view-title="Sign Up">
<ion-content ng-controller="signup">
<div class="figure_img">
<img src="img/logo_image.png">
</div>
<form name="myForm">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="Email ID" id="email" name="email" ng-model="formData.email"
required>
<span ng-show="myForm.email.$error.required && myForm.email.$dirty">required</span>
<span ng-show="!myForm.email.$error.required && myForm.email.$error.email && myForm.email.$dirty">invalid email</span>
</label>
<label class="item item-input">
<input type="password" placeholder="Password" id="password" name="password"
ng-model="formData.password" required>
<span ng-show="myForm.password.$error.required && myForm.password.$dirty">required</span>
</label>
<label class="item item-input">
<input type="password" placeholder="Confirm Password" id="password_c" name="password_c" ng-model="formData.password_c" valid-password-c required>
<span ng-show="myForm.password_c.$error.required && myForm.password_c.$dirty">Please confirm your password.</span>
<span ng-show="!myForm.password_c.$error.required && myForm.password_c.$error.noMatch && myForm.password.$dirty">Passwords do not match.</span>
</label>
<div class="contain-body">
<button class="button button-block button-positive" ng-click="signup(myForm)">SignUp</button>
</div>
</div>
</form>
</ion-content>
</ion-view>
this is my controller for signup
app.controller("signup", function ($scope,$http,$ionicPopup,URL,$ionicLoading,$timeout,$state) {
$scope.data = {
email :'',
password :''
};
$scope.signup = function (data) {
console.log(data);
$http.post(URL.url + '/registration',data)
.success(function () {
$ionicLoading.show({template:'<ion-spinner class="spinner-energized"></ion-spinner>Complete your Registration through Email'});
$timeout(function () {
$ionicLoading.hide();
$ionicHistory.clearCache().then(function() {
$state.go('EmailLogin') ;
});
},5000);
}).error(function (response) {
$ionicPopup.alert({
title: 'Sign-Up failed!',
template:response.errors.email
});
});
}
});
how could i take only password and username in my controller ..
so that it gets easy to signup !
You are actually passing the form controller to your signup method. This is not what you want.
You already got access to your email and password field values through formData.email and formData.password in your view, so you can adjust the call to the signup by including formData as suggested in the comments.
But as you declare $scope.data is your controller, you might want to reuse those instead of formData in your ng-model directive of the view, because currently this data object does not seem to be used.
Create an object in the function using the data you received. Just do something like var reqData = { email: data.email, password: data.password }; and then do $http.post(URL.url + '/registration',reqData).
Hope it helps.

Connect Express nodemailer with Angular

I'm trying to make a contact form, and the server side is working pretty well. But I don't know how to connect Angular to the html form and send it with Express. Any would appreciate any help.
My Express
router.get('/sendQuote', function(req, res) {
var data = req.query;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
});
So, my html:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">
And the main problem is here, how to glue Angular with HTML and Express. I can send emails, but get undefined in the fields of Name, Email and so on. :
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.sendMail = function () {
$scope.message = {};
$http.get('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
I think you should start by making this request a POST and not a GET request.
router.post('/sendQuote', function(req, res) {
var data = req.body;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
res.send(200); // let the client know it sent ok.
});
Now, let's take a look at your Angular code. It seems you want the object $scope.message to hold your form fields data. You should define this as an object at the beginning of your controller.
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.message = {};
$scope.sendMail = function () {
//$scope.message = {}; -- this was clearing the object
$http.post('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// you can clear $scope.message if you want here
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
HTML had one ng-model not binding to the message object:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="message.contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">

User login with Angularjs and Firebase

I am trying to find a way to create a simple login form with Angularjs and Firebase. I currently have a simple signup form, which adds a userName into my firebase database. All I need to know is how to get a login page that accepts a user once the userName is identified in the firebase system, and to possibly make a callback error if there is no such userName within the database. This is my signup form:
<html ng-app="myApp">
<body ng-controller="userCtrl">
<div class="centerForm">
<form>
<div class="form-group">
<label for="exampleInputUser">Username</label>
<input type="username" ng-model="userName" class="form-control" id="exampleInputUser" placeholder="username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" ng-model="userPassword" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<table class="nav" align="center">
<tr>
<td>
<p><button type="submit" class="btn btn-primary" ng-click="saveUser()">Submit</button>
Sign Up</p>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
and this is my sign up code:
<script>
angular.module('myApp', [])
.controller('userCtrl', function($scope) {
$scope.userName ="";
$scope.userPassword="";
$scope.myData = new Firebase( "https://myfirebaseapp.firebaseio.com/")
$scope.saveUser = function() {
$scope.myData.push({userName: $scope.userName});
};
});
</script>
My login form would then look something like:
<html ng-app="myApp">
<body ng-controller="userCtrl">
<div class="centerForm">
<form>
<div class="form-group">
<label for="exampleInputUser1">Username</label>
<input type="username" ng-model="userName" class="form-control" id="exampleInputUser1" placeholder="username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" ng-model="userPassword" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<table class="nav" align="center">
<tr>
<td>
<p><button type="submit" class="btn btn-primary" ng-click="loginUser()">Submit</button>
Sign Up</p>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
AngularFire exists for this reason- to bind Angular with Firebase.
Here's a working example. This is the login controller:
var app = angular.module('appName');
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://yourtester.firebaseio.com");
return $firebaseAuth(ref);
}
]);
app.controller('loginCtrl', ['$scope', '$state', '$http', 'Auth',
function($scope, $state, $http, Auth) {
$scope.auth = Auth;
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
});
$scope.login = function() {
Auth.$authWithPassword({
email: $scope.email,
password: $scope.password
})
.then(function(authData) {
console.log('Logged in as:', authData.uid);
//$state.go('profile');
})
.catch(function(err) {
console.log('error:',err);
//$state.go('login');
});
};
}
]);
And this is the login.html file:
<body ng-app='appName' ng-controller="loginCtrl">
<h1>Login!</h1>
<form ng-submit='login()'>
<div class="form-group">
<label for="email">Email address</label>
<input id="email" ng-model='email' type="email" placeholder="Email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input id="password" ng-model='password' type="password" placeholder="Password" required>
</div>
<button class="btn btn-success">Login</button>
</form>
I'm using angular JS and my login function for Firebase looks like this in the controller:
app.factory("Auth", ["$firebaseAuth",function($firebaseAuth) {
var ref = new Firebase("https://myfirebaseapp.firebaseio.com");
return $firebaseAuth(ref);
}]);
$scope.login = function() {
$scope.authObj.$authWithPassword({
name: $scope.data.name,
email: $scope.data.email,
password: $scope.data.password
}).then(function(authData) {
authenticated = true;
console.log("Logged in as:", authData.uid, authenticated);
$location.path("profile");
check();
}).catch(function(error) {
authenticated = false;
console.error("Authentication failed:", error);
check();
});
}

Resources