Angular form submissions issues - angularjs

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.

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"

Firebase createAuth credentials aren't working with ng-model scope variables

I'm using AngularFire in an Ionic project for the first time. I followed the example in the docs on the firebase website for Auth with email and password.For some reason my $scope values from ng-model aren't binding properly.
angular.module('starter')
.controller('RegisterController', ['Auth', '$scope', function(Auth, $scope) {
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$createUser({
email: $scope.email,
password: $scope.password
})
.then(function(userData) {
$scope.message = "User created: ";
})
.catch(function(error) {
$scope.error = error;
});
};
}]);
If I replace the $scope.email and $scope.password` with a hardcoded email and password it works. Here is the template with the email and password model data.
<ion-view view-title='Register A New Account' hide-back-button="false">
<ion-content class='padding'>
<div class="list list-inset">
<label class='item item-input'>
<span class='input-label'>Email</span>
<input type="text" placeholder='example#email.com' ng-model="email">
</label>
<label class='item item-input'>
<span class='input-label'>Password</span>
<input type="password" placeholder='' ng-model='password'>
</label>
<label class='item item-input'>
<span class='input-label'>Cell Phone</span>
<input type="tel" placeholder='316-333-3333'>
</label>
<label class='item item-input'>
<span class='input-label'>Date of Birth</span>
<input type="date">
</label>
<label class='item item-input'>
<span class='input-label'>City</span>
<input type="number" placeholder='Wichita'>
</label>
<label class='item item-input'>
<span class='input-label'>State</span>
<input type="number" placeholder='Kansas'>
</label>
<label class='item item-input'>
<span class='input-label'>Zipcode</span>
<input type="number" placeholder='67208'>
</label>
</div>
<ion-checkbox>
I agree to terms and conditions
</ion-checkbox>
<button class='button button-block button-calm' ng-click='createUser()'>Login</button>
<p ng-if='message'>Message: {{message}}</p>
<p ng-if='error'>Error: {{error}}</p>
</ion-content>
</ion-view>
Is my $scope value set wrong or is there something about the createAuth method that I am missing?
If anyone else runs into this problem it was a simple fix! I just had to make my $scope variables for email and password into a user object to access them using user.email. This state had a child scope that was conflicting.

Validating form on submit in angular

Hello i am trying to make my validation display on form submit but validation does not work, form gets sent anyway. This is my form:
<form class="form-horizontal col-md-10" role="form" name="authenticationForm" ng-controller="AuthenticationController as authentication" ng-submit="authenticate(authenticationForm.$valid)" novalidate>
<hr>
<br>
<div class="form-group" ng-class="{ 'has-error' : authenticationForm.email.$invalid && !authenticationForm.email.$pristine && submitted }">
<div class="col-md-4">
<label for="email">Email: </label>
</div>
<div class="col-md-6">
<input type="email" id="email" name="email" ng-model="email" class="form-control" ng-required/>
<p ng-show="authenticationForm.email.$invalid && !authenticationForm.email.$pristine && submitted" class="help-block">
Your email address is required.
</p>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : authenticationForm.password.$invalid && !authenticationForm.password.$pristine && submitted }">
<div class="col-md-4">
<label for="password">Password</label>
</div>
<div class="col-md-6">
<input type="password" id="password" name="password" ng-model="password" class="form-control" ng-required/>
<p ng-show="authenticationForm.password.$invalid && !authenticationForm.password.$pristine && submitted" class="help-block">
Password is required.
</p>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<span class="help-block errorMessages" ng-show="user.input.errors !== undefined">
<div class="alert alert-danger">
<ul class="list">
<li ng-repeat="error in user.input.errors">
<i class="fa fa-times"></i> <% error %>
</li>
</ul>
</div>
</span>
<div class="form-group">
<div class="col-md-12">
<br/>
<hr>
<button class="big-red-button" type="submit">Login <i class="glyphicon glyphicon-chevron-right"></i></button>
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
</div>
</form>
This is my controller function:
$scope.authenticate = function(isValid) {
// settting submitted to true
$scope.submitted = true;
// check to make sure the form is completely valid
if (isValid) {
var req = {
method: 'POST',
url: '/auth/login',
headers: {
'X-XSRF-Token': $("meta[name='csrf_token']").attr("content")
},
data: {
email: $scope.email,
password: $scope.password
}
}
$http(req)
.success(function (data, status, headers, config) {
if (data.url !== undefined)
{
window.location.href = data.url;
}
})
.error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
//alert(data);
});
}
};
Can someone please point out what i am doing wrong here? Thanks. :)
You should be able to check $scope.authenticationForm.$valid and prevent the xhr, and you can also visually set the submit button to ng-disabled="authenticationForm.$invalid" so they can't click the button until it's valid. That disabled setting won't prevent submitting the form other ways (enter key, etc).
Have you checked the boolean coming to you? It should be false is there's a validation error.
As you are using controllerAs syntax then you should use each ng-model as
authentication.email & authentication.password
Email Field
<input type="email" id="email" name="email" ng-model="authentication.email"
class="form-control" ng-required/>
Password Field
<input type="password" id="password" name="password" ng-model="authentication.password"
class="form-control" ng-required/>
then inside controller you could get this value by this.email & this.password
That happened to me too. Change ng-required to required, make sure the isValid boolean is actually false if it's not a valid form and take out the novalidate in the form element.
Sometimes the angular $valid is not always accurate. Also, I think you should have put ng-required="true" or some function that returns true, if you are using ng-required.
Check out this article: http://arnaldocapo.com/blog/post/detect-if-html-5-validation-ui-is-present/53
Just replace every where ng-required to required like:
<input type="text" required/>
and also set ng-controller="AuthenticationController " instead of
ng-controller="AuthenticationController as authentication"

Parsley Remote validation is not preventing form submission

I am using Parsley Remote validation with angularJS..using the async validator with add new user form is working fine, it uses the API and checks if the user name is already existed, and the email as well, if the user name is there it returns a 200 status, which is not equal to 404 and an error message appears.. BUT when submitting the form, if I check the form.isvalid status it returns true, it is only validating the NON remote options. I am stuck there.
here is the web form
<form class="form-horizontal form-label-left" method="post" id="AddUserForm"
data-ui-jq="parsley"
data-parsley-remote
data-parsley-priority-enabled="false"
novalidate="novalidate">
<fieldset>
<legend>
By default validation is started only after at least 3 characters have been input.
</legend>
<div class="form-group">
<label class="control-label col-sm-3" for="basic">User Name</label>
<div class="col-sm-9">
<input type="text" name="userName" class="form-control" data-ng-model="user.userName" value=""
data-parsley-remote
data-parsley-remote-validator='checkusername'
data-parsley-trigger="focusout"
data-parsley-remote-message="User name is already registerd in the system"
required="required" />
<span class="help-block">
Username must be unique
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="email">
E-mail
</label>
<div class="col-sm-9">
<input type="email" id="email" name="email" class="form-control" data-ng-model="user.email"
data-parsley-remote
data-parsley-remote-validator='checkemail'
data-parsley-trigger="focusout"
data-parsley-remote-message="Email is already registerd in the system"
required="required" />
<span class="help-block">
Email must be unique
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">
Password:
</label>
<div class="col-sm-9">
<input type="password" id="password" name="password" class="form-control mb-sm" data-ng-model="user.password"
data-parsley-trigger="change"
data-parsley-minlength="6"
required="required" />
<input type="password" id="password-r" name="password-r" class="form-control" placeholder="Confrim Password" data-ng-model="user.confirmPassword"
data-parsley-trigger="change"
data-parsley-minlength="6"
data-parsley-equalto="#password"
required="required" />
</div>
</div>
</fieldset>
<div class="form-actions">
<button type="submit" data-ng-click="AddNewUser($event)" class="btn btn-danger btn-rounded pull-right">Validate & Submit</button>
<button type="button" class="btn btn-default btn-rounded">Cancel</button>
</div>
</form>
and this is my async validator:
window.ParsleyExtend = {
asyncValidators: {
checkusername: {
fn: function (xhr) {
console.log($('[name="userName"]'));
return 404 === xhr.status;
},
url: authService.serviceBase + 'api/account/CheckUserName/' //+ $('[name="userName"]').text()
},
checkemail: {
fn: function (xhr) {
console.log($('[name="email"]'));
return 404 === xhr.status;
},
url: authService.serviceBase + 'api/account/CheckEmail/'// + $('[name="email"]').text()
}
}
};
and this is how I validate the form:
$scope.AddNewUser = function ($event) {
$event.preventDefault();
//THis resturns true allways when the remote validation is not valid,, but when other non remote valdiation happens is works fine
$('#AddUserForm').parsley().validate();
//and this if statement resturns true allways even when the remote validation is not valid,, but when other non remote valdiation happens is works fine
if ($('#AddUserForm').parsley().isValid()) {
authService.saveRegistration($scope.user).then(function (response) {
$scope.savedSuccessfully = true;
// $scope.message = "User has been registered successfully, you will be redicted to login page in 2 seconds.";
//startTimer();
},
function (response) {
var errors = [];
for (var key in response.data.modelState) {
for (var i = 0; i < response.data.modelState[key].length; i++) {
errors.push(response.data.modelState[key][i]);
}
}
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
just found the answer.. I have to use asyncIsValid() and asyncValidate() along with the normal isValid() and Validate() methods.. so the code will be as follows:
$('#AddUserForm').parsley().asyncValidate();
if($('#AddUserForm').parsley().isValid() && $('#AddUserForm').parsley().isAsyncValid()) {
....}
I first check each field to make sure it is validated, if a field is not validated, my ok variable will be set to false.
Here is some sample code:
$(function() {
var ok;
$('#signup').parsley().on('field:validated', function() {
ok = $('.parsley-error').length === 0;
})
.on('form:submit', function() {
if (ok) return true;
else return false;
});
});
Parsley.addAsyncValidator('checkExists', function(xhr) {
return false === xhr.responseJSON;
}, '/data-management/verify-data?filter=signup');

Form input is undefined

Why the name and password are undefined?
I've used ng-model on them...
<form class="login" name="form">
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="name">Name: </label>
<input type="text" ng-model="name" id="name" class="form-control" placeholder="Nitzan">
</div>
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="password">Password: </label>
<input type="password" ng-model="password" id="password" class="form-control" placeholder="1234">
<p class="help-block" ng-if="isInvalidLogin">Name or password are wrong!</p>
</div>
<button type="submit" class="btn btn-block btn-lg btn-success login-btn" ng-click="login()">Login</button>
</form>
In the controller:
$scope.login = function () {
usersService.get($scope.name, $scope.password).then(function success(result){
$scope.currentUser = result;
}, function error() {
$scope.isInvalidLogin = true;
});
};
See the plunker:
http://plnkr.co/edit/QD3vtil3w9pd4d1TGl9v?p=preview
Your problem is because of ng-if directive which is creating child scope from current scope. Hence $scope.name & $scope.password is undefined inside $scope.login function.
I'd suggest you do create one object for user which is initially blank like user={} or you can do this on html using ng-init, then put it inside of mainController so that it can directly access by the parent without doing $parent. notation.
And place name and password inside user object.
HTML
<div ng-init="user={}">
<div class="container login-div" ng-if="!currentUser">
<form class="login" name="form" ng-submit="login()">
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="name">Name:</label>
<input type="text" ng-model="user.name" id="name" class="form-control" placeholder="Nitzan">
</div>
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="password">Password:</label>
<input type="password" name="test" ng-model="user.password" id="password" class="form-control" placeholder="1234">
<p class="help-block" ng-if="isInvalidLogin">Name or password are wrong!</p>
</div>
<button type="submit" class="btn btn-block btn-lg btn-success login-btn">Login</button>
</form>
</div>
</div>
CODE
$scope.login = function () {
alert("Name "+ $scope.user.name +"& password is " +$scope.user.password)
//usersService.get($scope.name, $scope.password).then(function success(result){
// $scope.currentUser = result;
//}, function error() {
// $scope.isInvalidLogin = true;
//});
};
Working Plunkr here.
Update
Otherwise you need to add change your ng-model to refer this scope to parent scope like
HTML
For name ng-model="$parent.name"
For password ng-model="$parent.password"
CODE
$scope.login = function () {
alert("Name "+ $scope.name +"& password is " +$scope.password)
//usersService.get($scope.name, $scope.password).then(function success(result){
// $scope.currentUser = result;
//}, function error() {
// $scope.isInvalidLogin = true;
//});
};
Plunkr Here
Hope this could help you. Thanks.

Resources