Form Not Clearing after submit POST AngularJS - javascript

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

Related

How to compare values in Angularjs?

I'm a newbie to angular, so I need a help.
In html, I wrote the following
<div class="form-group">
<input type="email" name="Email" id="LoginEmail class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
In angular, I write the following code
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [
{name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"}
];
}]);
I need to compare the value of input box with the value of the script and show a message if it's not correct, so how can I do that?
Firstly you need to assign model to your template scope. Use ng-model for this purpose. Then you need a form to submit and trigger a function to check if user input matches to the desired values.
Add ng-model and wrap your inputs with a form tag:
<form ng-submit="login()">
<div class="form-group">
<input ng-model="email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
<button type="submit">Login</button>
</form>
Check if user input is valid in Controller:
$scope.login = function() {
const isUserValid = $scope.email === $scope.userinfo[0].account && $scope.password === $scope.userinfo[0].password;
if(isUserValid) {
alert("Logged In Successfully");
}else {
alert("Email or password incorrect. Try again.")
}
}
Here's a working example of the above code.
In your input elements you miss the ng-model attribute. It is used to bind the values with your scope variables.
<input type="email" ... ng-model="email" ...>
<input type="password" ... ng-model="password" ...>
And in your controller you can write
if($scope.email == $scope.userinfo[0].account && $scope.password == $scope.userinfo[0].password){
//Login ok
}else{
//Login failed
}
Assuming there is a form element somewhere above
Add ng-submit to it
<form ng-submit="submit()">
Add ng-model to the form elements.
I have added state.email and state.password
<div class="form-group">
<input ng-model="state.email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="state.password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
Compare the binding values to the values in $scope.userinfo
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [{
name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"
}];
// when you submit the form, this function will be called
$scope.submit = function (e) {
e.preventDefault();
if ($scope.state.email !== $scope.userinfo[0].account || $scope.state.password !== $scope.userinfo[0].password) {
// did not match
} else {
// matched
}
}
}]);

Display error message depending on if user is disabled or if input is invalid using JS/HTML

I want to display an error message under the 'Email Address' input if the user is disabled and display a separate error message if the user is invalid under the 'Password' input. When debugging I found that if a user is disabled the "Status code is 503" and if the input is invalid the "Status code is 400".
HTML
<md-content id="login" layout="column" layout-align="center center" class="inputdemoErrors">
<div flex="25"></div>
<p class="m0">project</p>
<form id="loginForm">
<md-input-container>
<label for="username">Email Address</label>
</md-input-container>
<md-input-container class="email-field">
<input name="username" id="username" type="email" class="validate" ng-model="username" enter-key="submitLogin()" autocomplete="off" required>
<div ng-show="disabled" ng-messages="loginForm.username.$error" role="alert">
<div ng-message="required">User Account is Disabled</div>
</div>
</md-input-container>
<md-input-container>
<label for="password">Password</label>
</md-input-container>
<md-input-container class="password-field">
<input name="password" id="password" type="password" class="validate" ng-model="password" enter-key="submitLogin()" autocomplete="off" required>
<div ng-show="invalid" ng-messages="loginForm.password.$error" role="alert">
<div ng-message="required">Invalid Email or Password</div>
</div>
</md-input-container>
<a class="waves-effect waves-light btn-large" style="width: 100%; margin: 0; background-color: #29B6F6;" ng-click="submitLogin()">Login</a>
</form>
</md-content>
JS
angular
.module('login')
.controller('LoginCtrl', LoginCtrl);
function LoginCtrl($scope, $location, SecService, RecService, Service) {
var vm = this;
vm.ctrlName = 'LoginCtrl';
$scope.submitLogin = function() {
$scope.invalid = $scope.loginForm.$invalid;
if($scope.invalid) {
return;
}
else
$scope.dataLoading = true;
var creds = {
username: $scope.username,
password: $scope.password
};
SecService.login(creds).then(function (response) {
if (response.success) {
RecService.connect();
SecService.setCredentials($scope.username, $scope.password);
Service.loadCurrentUser();
$location.path('/main');
}
if (response = 503)
{
$scope.disabled = $scope.loginForm.$disabled;
if ($scope.invalid) return invalid;
}
if (response = 400)
{
$scope.invalid = $scope.loginForm.$invalid;
if ($scope.invalid) return invalid;
}
});
};
}
}());
I am trying to display "User Account is Disabled" if the user is disabled (503), and "Email or Password is Invalid" if they have an invalid input (400). This should happen when the login button is clicked.
Hard to give a good answer without knowing what functionality you want with the ng-messages.
If you omit ng-messages:
<div ng-show="showDisabled">
User Account is Disabled
</div>
<div ng-show="showInvalid">
Invalid Email or Password
</div>
The following doesn't look right, so remove it for now:
if (response = 503)
{
$scope.disabled = $scope.loginForm.$disabled;
if ($scope.invalid) return invalid;
}
if (response = 400)
{
$scope.invalid = $scope.loginForm.$invalid;
if ($scope.invalid) return invalid;
}
It doesn't look like the return values are used anywhere and it should be response === x, not response = x.
Replace with:
$scope.showDisabled = response === 503;
$scope.showInvalid = response === 400;
Another note, if you need to access the form like this:
ng-messages="loginForm.password.$error"
The form needs a name:
<form name="loginForm">
Instead of id:
<form id="loginForm">

angularjs JavaScript inheritance, fail to bind data from view to a controller

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").

get input value after angularjs form validation

Hello everybody I'm quite new to Angularjs and Bootstrap. Now I have made login form using Angularjs and Bootstrap css.
The below is my form
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }">
<label>Username</label>
<input type="text" id="name" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }">
<label>Email</label>
<input type="email" id="email" name="email" class="form-control" ng-model="user.email">
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
<!-- PASSWORD -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
<label>Password</label>
<input type="password" id="pass" name="pass" class="form-control" ng-model="user.pass" ng-minlength="3" required>
<p ng-show="userForm.pass.$invalid && !userForm.pass.$pristine" class="help-block">Your pass is required.</p>
</div>
<button id="signIn_1" type="submit" class="btn btn-block signin">Submit</button>
</form>
and my app script is as
script>
// create angular app
var validationApp = angular.module('validationApp', []);
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.email = "fsdg#sdf.com";
$scope.password = "1234";
// function to submit the form after all validation has occurred
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
};
});
</script>
Now my problem is how can i get above form input values after validation in angular app and send them to Codeigniter controller for authenticate.
Thanks in advance.
first declare
$scope.user={} in validation controller
In user object all value is available to you when user type because of ng-model
validationApp.controller('mainController', function($scope) {
$scope.email = "fsdg#sdf.com";
$scope.password = "1234";
$scope.user={};//Add this thing
// function to submit the form after all validation has occurred
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
$http.post('index.php',$scope.user).success(function(response){
});
};
});
// At server end
// Remember one thing $http send data in json format.So decode it by json_decode

AngularJs + php authentication

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

Categories