Hi i started learning AngularJs and now im trying to do my Login module using angular and php, but i have some issues. I have watched alot tutorials but none of them was helpful in my case, so here is what i have: controllers.js:
var controllers = angular.module('controllers', []);
controllers.controller('loginController', ['$scope', '$http', 'UserService', function(scope, $http, User) {
scope.main = [
{username: '', password: ''}
]
scope.login = function(){
var config = {
url: '../auth/login.php',
method: 'POST',
data: {
username: scope.main.username,
password: scope.main.password
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}
$http(config)
.success(function(data,status,headers,config){
if(data.status){
//succefull login
User.isLogged = true;
User.username = data.username;
}
else{
User.isLogged = false;
User.username = '';
}
})
.error(function(data,status,headers,config){
User.isLogged = false;
User.username = '';
});
}
}])
auth.js:
var services = angular.module('services', []);
services.factory('UserService', [function(){
var sdo = {
isLogged: false,
username: ''
};
return sdo;
}]);
login.php:
$username = $_POST['username'];
if($username){
return "Logged";
}else{
return false;
}
and the html:
<div class="col-xs-12" id="loginCol" ng-controller="loginController">
<form ng-submit='login()' name="form" novalidate>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" ng-model="scope.main.username" class="form-control" id="username" placeholder="Име..." />
<label for="password" class="sr-only">Password</label>
<input type="password" ng-model="scope.main.password" class="form-control" id="password" placeholder="Парола..." />
</div>
<div class="form-group pull-right">
<button type="button" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-default">Register</button>
</div>
</form>
</div>
In this case i want just if user type something in the username input and hit the login button and on successful call of login.php to return some message. The problem is that code written like that got error "'loginController' is not a function, got undefined" how to fix it?
(Disclosure: I'm one of the developers of UserApp)
You could try the third-party service UserApp, together with the AngularJS module.
Check out the getting started guide, or take the course on Codecademy. Here's some examples of how it works:
Login form with error handling:
<form ua-login ua-error="error-msg">
<input name="login" placeholder="Username"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Log in</button>
<p id="error-msg"></p>
</form>
Signup form with error handling:
<form ua-signup ua-error="error-msg">
<input name="first_name" placeholder="Your name"><br>
<input name="login" ua-is-email placeholder="Email"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Create account</button>
<p id="error-msg"></p>
</form>
ua-is-email means that the username is the same as the email.
How to specify which routes that should be public, and which route that is the login form:
$routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
$routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
The .otherwise() route should be set to where you want your users to be redirected after login. Example:
$routeProvider.otherwise({redirectTo: '/home'});
Log out link:
<a href="#" ua-logout>Log Out</a>
Access user properties:
User info is accessed using the user service, e.g: user.current.email
Or in the template: <span>{{ user.email }}</span>
Hide elements that should only be visible when logged in:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show an element based on permissions:
<div ua-has-permission="admin">You are an admin</div>
And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API with the PHP library to check if the token is valid or not.
If you need any help, just let me know :)
You have created the application
var controllers = angular.module('controllers', []);
but didn't use it in the html code, add ng-app attribute to the wrapper div
<div class="col-xs-12" ng-app="controllers" id="loginCol" ng-controller="loginController">
the second issue, that you try to catch submit event, but don't submit the form, use submit type instead button
<button type="submit" class="btn btn-primary">Login</button>
or add ng-click="login()" attribute to the button and remove ng-submit='login()' from the form
Related
I am currently trying to create a user login page where the user information is stored on a json file. I have created my GET method to the file but I cannot seem to redirect after the user has logged in successfully. Can you help me out?
I know that user login and validation done on the client side is A BAD IDEA but that is how I want to do it, without using a database.
Here is my HTML code:
<body ng-controller="myCtrl">
<form id="login-form">
<h3>User Login</h3>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button type="submit" class="btn btn-default" id="login-button" ng-click="LogOn()">Login</button>
</form>
</body>
My JavaScript code:
var app = angular.module('myApp', [ ]);
app.controller("myCtrl",['$scope', '$http', function($scope, $http){
$scope.LogOn = function(){
$http.get('data.json').then(function(data){
$scope.users = data;
});
if (data.email == email) && (data.password = password{
window.location.href = 'www.google.com';
}
};
}]);
My JSON File:
[
{
"email":"something#yahoo.com",
"Password":"password"
},
{
"email":"test#yahoo.com",
"password":"test999"
},
{
"email":"xxx#mail.xx",
"password":"xxx"
}
]
Please try to open the link and check and run the code which is deployed in w3 schools
https://www.w3schools.com/code/tryit.asp?filename=FDVZY3NXVYG6
Put redirection code inside then
$http.get('data.json').then(function(data){
$scope.users = data;
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
});
Obviously the if bellow has to be inside the .then( callback
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
I was wondering, what's the clean way of posting form data with angular?
I have this form setup
<div id="contact-form" class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
<form>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Firstname" name="firstname" ng-model="firstname">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Lastname" name="lastname" ng-model="lastname">
</div>
<div class="form-group">
<input type="email" class="form-control input-lg text-center" placeholder="Email" name="email"ng-model="email">
</div>
<!-- Submit Contact -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createContact()">Add</button>
</form>
</div>
</div>
and I'm posting this to a node.js backend "api".
How do I do this correctly? Do I write every api request in 1 core file? Do I make separate files for each page?
And then how I do I write a clean request?
$scope.createContact = function() {
$http.post('/contacts', ...)
.success(function(data) {
})
.error(function(data) {
});
};
I want to process 'lastname', 'firstname' and 'email' to add a new contact, but online I can't find a good, clean way to write this.
Here's my model in case it helps:
var mongoose = require('mongoose');
var ContactSchema = new mongoose.Schema({
firstname: { type: String, require: true },
lastname: { type: String, require: true },
email: { type: String, require: true }
});
module.exports = mongoose.model('Contact', ContactSchema);
Here's the code I used in the end.
$scope.createContact = function(contact) {
$scope.contact = { firstname: $scope.firstname, lastname: $scope.lastname, email: $scope.email };
$http.post('/contacts', $scope.contact)
.success(function(data) {
$scope.contact = {firstname:'',lastname: '', email:''}; // clear the form so our user is ready to enter another
$scope.contacts = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
How you structure your project is up to you. You could do it all in one file (but that's not very scalable), You could do one in each file (I wouldn't recommend it), or you could group them into semantic files like user_routes.js, social_media_routes.js, etc.
You are on the right track using $http.post() You'll want to create a JSON using your bound variables. You haven't included your entire controller so it's hard to tell you what to do. But a better way of doing this would probably just to create a JSON with empty values like this:
$scope.contact = {
firstname: '',
lastname: '',
email: '',
}
and then use something like ng-model="contact.firstname" for your data-binding. This will let you simply send $scope.contact to the back-end route.
The back-end route in Express would look something like:
var express = require('express');
var app = express();
app.post('/contacts', function (req, res) {
res.status(200).send(req)
}
This will send back what it receives - That should be enough to get you started - Handling POST requests in Express will depend on what version of Express you are using.
In the form tag add the attribute ng-submit to trigger directly in angular the post function.
<div id="contact-form" class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
<form ng-submit="createContact(user)">
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Firstname" name="firstname" ng-model="user.firstname">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Lastname" name="lastname" ng-model="user.lastname">
</div>
<div class="form-group">
<input type="email" class="form-control input-lg text-center" placeholder="Email" name="email"ng-model="user.email">
</div>
<!-- Submit Contact -->
<button type="submit" class="btn btn-primary btn-lg">Add</button>
</form>
</div>
Add an empty user object in the controller:
$scope.user = {firstname:'',lastname: '', email:''};
Let the $http service handle the call:
$scope.createContact = function(user) {
$http.post('/contacts', user)
.then(function(data) {
//in data.data is the result of the call
},function(error) {
//here is the error if your call dont succeed
});};
I am trying to create a new user in Angular. I'm attempting to send a POST request to my api through the client side to create a new user. Unfortunately I can't successfully send the post request. Sending the request through Postman is successful, but not through Angular. Any ideas on what could be the issue? Any help is appreciated.
userCtrl.js
//./public/app/controllers/userCtrl.js
angular.module('userCtrl',['userService'])
//SIGN UP CTRL ================================
//inject the User factory
.controller('userCreateController', function($location, User){
var vm = this;
//Function that creates a new user
vm.saveUser = function(){
//For spinner animation when signing up
vm.processing = true;
//Use the create funciton in the userService
User.create(vm.userData)
.then(function(data){
if(data.success){
$location.path('/login');
}else {
console.log('error');
vm.processing = false;
}
})
}//End saveUser
})//End userCreateController
userService.js
//userService.js
angular.module('userService', [])
.factory('User', function($http){
//create a user factory object
var userFactory = {};
//get a single user
userFactory.get = function(id){
return $http.get('/api/users/' + id);
};
//get all users
userFactory.all = function(){
return $http.get('/api/users/');
};
//create a user
userFactory.create = function(userData){
return $http.post('/api/users/', userData);
};
//update a user
userFactory.update = function(id, userData){
return $http.put('/api/users/' + id, userData);
};
//delete a user
userFactory.delete = function(id){
return $http.delete('/api/users' + id);
};
//return userFactory object
return userFactory;
});
routes.js
//./public/app/routes.js
angular.module('appRoutes', ['ngRoute'])
.config(function($routeProvider, $locationProvider){
$routeProvider
//homepage route
.when('/',{
templateUrl : 'app/views/pages/home.html'
})
.when('/login',{
templateUrl: 'app/views/pages/login.html',
controller: 'mainController',
controllerAs: 'login'
})
.when('/signup',{
templateUrl: 'app/views/pages/signup.html',
controller: 'userCreateController',
controllerAs: 'signup'
})
//Remove hash in the Url
$locationProvider.html5Mode(true);
})//End config
signup.html
<div class="row col-sm-6 col-sm-offset-3">
<div class="jumbtron">
<h1>Sign Up</h1>
<!-- Sign Up Form -->
<form ng-submit='signup.saveUser()'>
<!-- Name Input -->
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Enter Your Name" ng-model='signup.userData.name'>
</div>
<!-- Username Input -->
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Enter Username" ng-model='signup.userData.username'>
</div>
<!-- Password Input -->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Enter Password" ng-model='signup.userData.password'>
</div>
<!-- Signup Button -->
<button type="submit" class="btn btn-block btn-success">
<!-- Show SignUP -->
<span ng-if="!signup.processing">Sign Up</span>
<!-- Show spinner animation when signing up -->
<span ng-if="signup.processing" class="spinner">
<span class="glyphicon glyphicon-repeat"></span>
</span>
</button>
</form>
<!-- End Sign Up Form -->
</div>
</div>
It is difficult to say without more information like the browser console log, but if you are minifying the code, it could be due to the implicit annotation syntax used in the controller injection.
Try to write it with the preferred Inline Array Annotation like:
.controller('userCreateController',
['$location', 'User', function($location, User){
...
}]);
at signup.html you are modifying signup.userData.* but at userCtrl.js you are sending vm.userData instead of $scope.signup.userData.
The problem could be that you are sending an undefined object instead of the userData object.
I'm using angularjs frontend and Play framework backend to process posted data.
The challenge i'm facing is that the form is not resetting after successful posting of data I click submit.
My View is as below and is as below.
<form name="signupForm" ng-submit="signup()" novalidate>
<div>
<label for="email">Email</label>
<input name="email" class="form-control" type="email" id="email" placeholder="Email"
ng-model="email">
</div>
<div>
<label for="password">Password</label>
<input name="password" class="form-control" type="password" id="password"
placeholder="Password" ng-model="password">
</div>
<button type="submit" class="btn btn-primary">Sign up!</button>
</form>
My Angular controller is as below
angular.module('clientApp')
.controller('SignupCtrl', function ($scope, $http, $log) {
$scope.signup = function() {
var payload = {
email : $scope.email,
password : $scope.password
};
$http.post('app/signup', payload)
.success(function(data) {
$log.debug(data);
});
};
});
I'm using chrome browser. How do i get to clear the email and password fields after clicking submit?
Set the $scope.email and $scope.password to null like
$http.post('app/signup', payload)
.success(function(data) {
$log.debug(data);
$scope.email = null;
$scope.password = null;
$scope.signupForm.$setPristine(); //Set form to pristine mode
});
what am trying to do is to get data from the form use it in my controller in HTTP post call but it's not working
I know i might have problem with inheritance of scopes but icant solve it.
here is my controller code:
.controller('SignUpCtrl', function($scope, $http, $state) {
$scope.submit = function() {
var url = 'http://localhost:3000/register';
var user = {
email: $scope.email,
password: $scope.password,
};
console.log($scope.user);
$http.post(url, user)
.success(function(res){
console.log('You are now Registered');
//$state.go('app.items');
})
.error(function(err){
console.log('Could not register');
// $state.go('error');
});
};
})
Here is the code of my Template:
<form name="register">
<div class="list">
<label class="item item-input no-border">
<input name="fullname" type="text" ng-model="fullname" placeholder="Full Name" required="">
</label>
<label class="item item-input">
<input name="email" type="email" ng-model="user.email" placeholder="Email" required="">
</label>
<p class="blue-font" ng-show="register.email.$dirty && register.email.$invalid">Please Write valid Email.</p>
<label class="item item-input">
<input name="password" type="password" ng-model="user.password" placeholder="Password" required="">
</label>
<button ng-click="submit();" ng-disabled="register.$invalid" type="submit" class="button signup-btn sharb-border white-font blue-bg-alt border-blue-alt ">
Sign Up
</button>
</div>
</form>
Note: i tried the ng-submit its not really the problem
Inside the controller.
.controller('SignUpCtrl', function($scope, $http, $state) {
$scope.user = {
email: '',
password: ''
};
$scope.submit = function() {
And this
var user = {
email: $scope.user.email,
password: $scope.user.password
};
Also drop the ; in ng-click
<button ng-click="submit()" ...>
Try to use rootScope (docs.angularjs.org/$rootScope").