Grab all input data with Angular - javascript

Im trying to post input data with angular, but I don't know how to grab the data from the input fields.
Here is my HTML:
<div ng-controller="Test">
<div class="container">
<div class="col-sm-9 col-sm-offset-2">
<div class="page-header"><h1>Testar</h1></div>
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<div class="form-group" ng-class="{'has-error' : userForm.name.$invalid && !userForm.name.$pristine, 'has-success' : userForm.name.$valid }">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">Fel namn</p>
</div>
<div class="form-group" ng-class="{'has-error' : userForm.username.$invalid && !userForm.username.$pristine, 'has-success' : userForm.username.$valid && !userForm.username.$pristine}">
<label>Username</label>
<input type="text" 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">För kort</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">För långt</p>
</div>
<div class="form-group" ng-class="{'has-error' : userForm.email.$invalid && !userForm.email.$pristine, 'has-success' : userForm.email.$valid && !userForm.email.$pristine}">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="email">
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Ange korrekt e-post</p>
</div>
<button type="submit" class="btn btn-primary">Lägg till</button>
</form>
</div>
</div>
</div>
Here is my controller:
as.controller('Test', function($scope, $http, $rootScope)
{
$scope.submitForm = function(isValid) {
if(isValid)
{
$http.post($rootScope.appUrl + '/nao/test', {"data": $scope.userForm})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status) {
});
}
};
});
A post is made when I hit the button, but the data that Is being sent looks like this:
{"data":{"name":{},"username":{},"email":{}}}
How can I take the data from all the input fields? Should I refer to userForm as I do in the controller?

I suggest to create one more $scope object - at beginning it will be empty:
$scope.form = {};
Every field will be a part of this object:
<input type="text" name="name" class="form-control" ng-model="form.name" required>
After send all fields you will have in object $scope.form.
jsFiddle: http://jsfiddle.net/krzysztof_safjanowski/QjNd6/

you have ng-model variables in scope:
$scope.name
$scope.user.username
$scope.email
you can all of these prefix with user. and then send with ajax $scope.user instead of $scope.userForm
or
try to send object which is copied by: angular.copy($scope.userForm)

You can have a property in your scope, say user. Have all your ng-model values be user.SOMETHING. This way you can easily send the $scope.user holding all the data, as in {data: $scope.user }.

Related

how can i do select options required & Email validation in angular js?

when clicked on submit button, it will call function, in that function i am trying to write logic to disable submit button when fields are not valid, here email must be contain #, dot and after dot minimum 2 & maximum 4 alphabet characters. I tried bellow code.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
<div>
<select id="country" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)"
ng-required>
<option ng-repeat="(key,country) in countries" value="{{key}}">{{country[0]}}</option>
</select>
</div>
<div>
<select id="state" ng-disabled="!states[state1].length" ng-model="cities" ng-required>
<option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
</select>
</div>
<input type="email" ng-disable="myForm.user.email.$valid" ng-model="user.email" name="eamil" ng-required/>
<button ng-disable="myForm.user.email.$valid" ng-click="formsubmit();">submit</button>
</form>
</div>
SCRIPT:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.formsubmit = function () {
}
$scope.states = {
"IN": [
"Delhi",
"Goa",
"Gujarat",
"Himachal Pradesh",
]
};
$scope.countries = {
IN: ["India"],
ZA: ["South Africa"],
AT: ["Austria"]
}
$scope.state1 = Object.keys($scope.countries)[0];
$scope.lastName = "Doe";
});
jsfiddle
<form role="form" name="signupForm" ng-submit="signup()" novalidate>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="clearfix"> </div>
<div class="inputGroup">
<input type="text" id="su_username" name="username" class="form-control input-md"
ng-model="user.username" ng-minlength="8" required>
<span class="inputBar"></span>
<label translate="signup.form.username">Username</label>
<span class="text-danger" ng-show="signupForm.username.$dirty && signupForm.username.$invalid">
<span ng-show="signupForm.username.$error.required" translate="signup.messages.validate.username.required">Username is required.</span>
<span ng-show="signupForm.username.$error.minlength" translate="signup.messages.validate.username.minlength">Username must be at least 8 characters.</span>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="clearfix"> </div>
<div class="inputGroup">
<input type="email" name="email" id="su_email" class="form-control input-md"
ng-model="user.email" required>
<span class="inputBar"></span>
<label translate="signup.form.email">Email Address</label>
<span class="text-danger" ng-show="signupForm.email.$dirty && signupForm.email.$invalid">
<span ng-show="signupForm.email.$error.required" translate="signup.messages.validate.email.required">Email is required.</span>
<span ng-show="signupForm.email.$error.email" translate="signup.messages.validate.email.invalid">Invalid email address.</span>
</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-custom btn-lg btn-block"
ng-disabled="signupForm.$invalid ">
1st of all you need to give your form a name here its signupForm .
2nd from there you need to give your input fields names for example here they areusername and email.
Then you can use various angular validation directives to set validation constrains like require , length then you can check for validation error using signupForm.username.$invalid and check various error like signupForm.email.$error.email.
Finally if you want to check if the whole from is valid use signupForm.$invalid
and for number validation use
angular.module('test')
.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
val = '';
}
var clean = val.replace( /[^0-9\.]/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
you can find github example from here
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function() {
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
</head>
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as demo">
<form name="form" novalidate ng-submit="validate()">
<input type="email" name="email" ng-model="email" required />
<span class="help-inline" ng-show="submitted && form.email.$error.required">Required</span>
<span class="help-inline" ng-show="submitted && form.email.$error.email">Invalid email</span>
<button type="submit" class="btn btn-primary btn-large" ng-disabled="submitted && form.email.$error.required || submitted && form.email.$error.email" ng-click="submitted=true">Submit</button>
</form>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
</body>
</html>
Check This Out.
In order to disable the submit button, you can do something like this:
<form name="myForm">
<input ...>
...
<button type="button" ng-disabled="myForm.$invalid" ng-click="formsubmit();">
Submit
</button>
</form>
Notice that I have put ng-disabled with a condition of myForm being invalid. So, instead of waiting for user to click the button, we are disabling the submit button upfront when form is invalid!
For Email validation, I would suggest you to go with <input type = "email"...> unless you have specific email validation requirements not handled by type = "email"
Here's the updated fiddle which disables the submit button until we put a valid email address.
Edit: Here's an example of how ng-pattern can be used to validate email for given rules (i.e. email must contain #, dot and after dot minimum 2 & maximum 4 alphabet characters)
<input type="text" ng-model="user.email" name="email" required
ng-pattern="/[a-zA-Z0-9_.]+\#[a-zA-Z0-9_]+\.[a-zA-Z]{2,4}$/"/>
Here's the updated fiddle
Also, regex101 for the email validation regex

AngularJS - submit form programmatically after validation

I have recently started working on AngularJS 1.6.
I am trying to submit a form programmatically. The reason is I want to validate a few fields (required field validation). I have spent a lot of efforts (probably 3-4 hours) trying to make this work but none of the existing answers on stack overflow or AngularJS docs seems to be working for me today (strange), hence I am posting this as last resort.
Below is my html
<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
<div>
{{message}}
</div>
<div>
<label>User Name</label>
<input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" />
</div>
<div>
<label>Password</label>
<input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" />
</div>
<div>
<input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" />
</div>
</form>
My angular code
var demoApp = angular.module('demoApp', []);
demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {
$scope.loginUser = function () {
var form = document.getElementById("loginform");
//var form = $scope.loginform; - tried this here...
//var form = $scope["#loginform"]; tried this
//var form = angular.element(event.target); - tried this...
// tried a lot of other combinations as well...
form.attr("method", "post");
form.attr("action", "Home/Index");
form.append("UserName", $scope.user.UserName);
form.append("Password", $scope.user.Password);
form.append("RememberMe", false);
form.submit();
};
}]);
I keep on getting error 'attr' is not a function.
All I need is submit a form using post method, with values. Just before that I am trying to intercept the submit call and check for validations.
I am open to try any other approach as well. Such as changing the input type from submit to button. Putting the input outside the form. I would be more than happy if validations and submit both can happen any which way. I just want it to post back the values after validating on the client side and then the server will take care of the redirect.
Note: I want the form to do a full postback so that I can get it to redirect to another form. (I know I could use Ajax, but some other day, may be!)
1st of all avoid doing var form = document.getElementById("loginform");. Instead of using form.submit you can use the following code. Do it the angular way cheers :D
$scope.loginUser = function () {
if($scope.loginform.$valid){
user.rememberme=false;
$http({
url: 'Home/Index',
method: "POST",
data: user
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
}
};
this is a code to validation if validation not complate button is not enable
<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
<div>
{{message}}
</div>
<div>
<label>User Name</label>
<input type="text" id="txtUserName" required ng-model="user.UserName" name="UserName" />
</div>
<div>
<label>Password</label>
<input type="text" id="txtPassword" ng-model="Password" name="user.Password"required />
</div>
<div>
<input type="submit" ng-disabled="myForm.UserName.$invalid || myForm.Password.$invalid" id="btnLogin" title="Save" name="btnLogin" value="Login" />
</div>
</form>
You should use $scope when trying to access the form, something like $scope.loginform. But......
Take a look at ng-messages. Heres an example using ng-messages with your form:
<form id="loginform" name="loginform" ng-submit="loginUser()">
<div>
{{message}}
</div>
<div>
<label>User Name</label>
<input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" required/>
<div class="help-block" ng-messages="loginform.txtUserName.$error" ng-show="loginform.txtUserName.$touched">
<p ng-message="required">Username is required.</p>
</div>
</div>
<div>
<label>Password</label>
<input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" required/>
<div class="help-block" ng-messages="loginform.txtPassword.$error" ng-show="loginform.txtPassword.$touched">
<p ng-message="required">Password is required.</p>
</div>
</div>
<div>
<input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" ng-click="loginUser()" />
</div>
</form>
Add ngMessages:
var demoApp = angular.module('demoApp', ['ngMessages']);
demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {
$scope.loginUser = function () {
if($scope.loginform.$valid){
//Code to run before submitting (but not validation checks)
} else{
return false;
}
};
}]);
Don't forget to include ngMessages in your app declaration and include the ngMessages.js script file. Note how you can simply use HTML5 validators.
I found the thing I was looking for. In the end I had to create a directive for validating and then submitting. So I am posting it here as a whole answer.
My HTML
<div ng-controller="homeController" ng-init="construct()">
<form method="post" action="Index" role="form" id="loginform" name="loginform" ng-form-commit novalidate class="ng-pristine ng-invalid ng-invalid-required">
<div class="form-group">
<label for="UserName">User ID</label>
<input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
id="UserName" name="UserName" ng-model="user.UserName" type="text" value=""
ng-change="userNameValidation = user.UserName.length == 0">
<span class="field-validation-error text-danger" ng-show="userNameValidation">The User ID field is required.</span>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
id="Password" name="Password" ng-model="user.Password" type="password" value=""
ng-change="passwordValidation = user.Password.length == 0">
<span class="field-validation-error text-danger" ng-show="passwordValidation">The Password field is required.</span>
</div>
<div>
<input type="button" id="btnLogin" title="Login" name="btnLogin" value="Login" ng-click="validateUser(loginform)" />
</div>
</form>
</div>
Look for ng-form-commit on the form element. It is the directive that I created.
My Angular code
var demoApp = angular.module('demoApp', []);
demoApp.factory("commonService", function () {
return {
isNullOrEmptyOrUndefined: function (value) {
return !value;
}
};
});
//This is the directive that helps posting the form back...
demoApp.directive("ngFormCommit", [function () {
return {
require: "form",
link: function ($scope, $el, $attr, $form) {
$form.commit = function () {
$el[0].submit();
};
}
};
}]);
demoApp.controller("homeController", ["$scope", "commonService", function ($scope, commonService) {
$scope.construct = function construct() {
$scope.user = { UserName: "", Password: "" };
};
$scope.userNameValidation = false;
$scope.passwordValidation = false;
$scope.isFormValid = false;
$scope.validateUser = function ($form) {
$scope.isFormValid = true;
$scope.userNameValidation = commonService.isNullOrEmptyOrUndefined($scope.user.UserName);
$scope.passwordValidation = commonService.isNullOrEmptyOrUndefined($scope.user.Password);
$scope.isFormValid = !($scope.userNameValidation || $scope.passwordValidation);
if ($scope.isFormValid === true) {
$scope.loginUser($form);
}
};
$scope.loginUser = function ($form) {
$form.commit();
};
}]);
I found the directive here
Example using Angular 1.5 components.
(function(angular) {
'use strict';
function DemoFormCtrl($timeout, $sce) {
var ctrl = this;
this.$onInit = function() {
this.url = $sce.trustAsResourceUrl(this.url);
/*$timeout(function() {
ctrl.form.$$element[0].submit();
});*/
};
this.validate = function(ev) {
console.log('Running validation.');
if (!this.form) {
return false;
}
};
}
angular.module('app', [])
.component('demoForm', {
template: `
<p>To run this demo allow pop-ups from https://plnkr.co</p>
<hr>
<p>AngularJS - submit form programmatically after validation</p>
<form name="$ctrl.form" method="get" target="blank" action="{{::$ctrl.url}}" novalidate
ng-submit="$ctrl.validate($event)">
<input type='hidden' name='q' ng-value='::$ctrl.value'>
<input type='hidden' name='oq' ng-value='::$ctrl.value'>
<input type="submit" value="submit...">
</form>`,
controller: DemoFormCtrl,
bindings: {
url: '<',
value: '<'
}
});
})(window.angular);
https://plnkr.co/edit/rrruj6vlWrxpN3od9YAj?p=preview

AngularJS Validation trouble

I have a form which seems to work well on the most part. However, my selects are playing up a bit, and I cant seem to submit the form. My form looks like
<form ng-submit="submit(emailform)" name="emailform" method="post" action="" class="form-horizontal emailType" role="form">
<div class="form-group" ng-class="{ 'has-error': emailform.inputTitle.$invalid && submitted }">
<label for="inputTitle" class="col-lg-4 control-label">Title</label>
<div class="col-lg-8">
<select ng-model="formData.inputTitle" data-ng-options="title for title in titles" id="inputTitle" required>
<option value="">Please select</option>
</select>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': emailform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-4 control-label">First Name(s)</label>
<div class="col-lg-8">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="First Name(s)" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': emailform.inputLinks.$invalid && submitted }">
<label for="inputLinks" class="col-lg-4 control-label">Link to be sent</label>
<div class="col-lg-8">
<select ng-model="formData.inputLinks" data-ng-options="link for link in links" id="inputLinks" required>
<option value="">Please select</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
Send Message
</button>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
So a simple form with two selects and one input. My Controller looks like the following
'use strict';
/* Controllers */
function EmailViewCtrl($scope, $http) {
$scope.titles =
[
"Mr",
"Mrs",
"Miss",
"Ms",
"Dr"
];
$scope.links =
[
"email1",
"email2",
"email3",
"email4",
"email5"
];
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(emailform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (emailform.$valid) {
$http({
method : 'POST',
url : 'backend/email.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.';
$scope.result='bg-danger';
}
}
}
EmailViewCtrl.$inject = ['$scope', '$http'];
Now the problem is, my selects on their default option (please select) have a red border around them on page load. Obviously this should not appear until they submit the form without an option selected.
Secondly, if I provide the form with valid data, the submit button does not seem to become active. How can I make this active?
Lastly, at the moment, everything is in one controller. Should I move things like the selects values into their own controller and what would be the best way to achieve this?
Thanks
You can use form.input.$dirty to check if an input has been touched and only in that case show a validation error.
ng-class="{ 'has-error': emailform.inputName.$invalid && emailform.inputName.$dirty }"
See the example below for a working copy of your code:
var app = angular.module("app", []);
app.controller("EmailViewCtrl", function EmailViewCtrl($scope, $http) {
$scope.titles = [
"Mr",
"Mrs",
"Miss",
"Ms",
"Dr"
];
$scope.links = [
"email1",
"email2",
"email3",
"email4",
"email5"
];
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(emailform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (emailform.$valid) {
alert("POST!");
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="EmailViewCtrl">
<form ng-submit="submit(emailform)" name="emailform" method="post" action="" class="form-horizontal emailType" role="form">
<div class="form-group" ng-class="{ 'has-error': emailform.inputTitle.$invalid && emailform.inputTitle.$dirty }">
<label for="inputTitle" class="col-lg-4 control-label">Title</label>
<div class="col-lg-8">
<select class="form-control" ng-model="formData.inputTitle" data-ng-options="title for title in titles" id="inputTitle" required>
<option value="">Please select</option>
</select>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': emailform.inputName.$invalid && emailform.inputName.$dirty }">
<label for="inputName" class="col-lg-4 control-label">First Name(s)</label>
<div class="col-lg-8">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="First Name(s)" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': emailform.inputLinks.$invalid && emailform.inputLinks.$dirty }">
<label for="inputLinks" class="col-lg-4 control-label">Link to be sent</label>
<div class="col-lg-8">
<select class="form-control" ng-model="formData.inputLinks" data-ng-options="link for link in links" id="inputLinks" required>
<option value="">Please select</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
Send Message
</button>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>

Angularjs - form validation

im trying to validate my users inputs and it works greate that the user can press the submit btn and it errors the input fields that is missing so the user know what input he is missing.
My problem is that it only works when i remove action="/buy" method="post" but i need it to normal submit the form when there is no errors.
How can i do that?
Im using this form validation with angularjs validate http://www.brentmckendrick.com/code/xtform/
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<label class="control-label" for="textinput">Fornavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('fornavn'); ?>" name="fornavn" ng-model="fornavn" class="form-control" xt-validate required>
</div>
<button id="membership-box__payBtn" type="submit" name="betaling" class="btn btn-success text-uppercase">Go to payment</button>
</form>
Well you can use the $http service to send any type of request to server. When you actually do form post data is posted with content-type:'application/x-www-form-urlencoded'.
For your request if you can set the correct content-type and encode the object to send correctly, it would work. See this fiddle i created earlier that sends data to server as standard form post.
http://jsfiddle.net/cmyworld/doLhmgL6/
The relevant $http request looks like
$scope.update = function (user) {
$http({
method: 'POST',
url: 'https://mytestserver.com/that/does/not/exists',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (data) {
var postData = [];
for (var prop in data)
postData.push(encodeURIComponent(prop) + "=" + encodeURIComponent(data[prop]));
return postData.join("&");
},
data: user
});
You can model your input fields, and delegate each field to your model as:
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<input autocomplete="off" type="text" name="fornavn" ng-model="fornavn.input1" class="form-control" xt-validate required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn2.$invalid && !userForm.fornavn2.$pristine }">
<input autocomplete="off" type="text" name="fornavn2" ng-model="fornavn.input2" class="form-control" xt-validate required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn3.$invalid && !userForm.fornavn3.$pristine }">
<input autocomplete="off" type="text" name="fornavn3" ng-model="fornavn.input3" class="form-control" xt-validate required>
</div>
<button id="membership-box__payBtn" type="submit" name="betaling" class="btn btn-success text-uppercase">Go to payment</button>
</form>
And in your controller, send data using $http as:
var baseUrl=<yourBaseUrl>;
var url = baseUrl+'/buy';
var data = $scope.fornavn;
if(!$scope.userForm.$invalid){
$http.post(url, data).
success(function(data) {
if (data.error_msg) {
alert(data.error_msg);
}else{
alert("Successful! ");
}
}).
error(function(data) {
alert('error');
});
}

angularjs form reset error

i'm trying to do a form with validations using angularjs and so far i did a good job. But when i commit my reset button all the fields reset except for the error messages i get from my validation part. How can i get rid of all the fields and error messages when i reset my form.
This is how it is when i press my reset button
this is my code
<div class="page-header"><center><h2>Give us your Feedback</h2></center></div>
<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
<label>Name*</label>
<input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block">
<font color="#009ACD">You name is required.</font>
</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty }">
<label>Email</label>
<input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">
<font color="#009ACD">Enter a valid email.</font>
</p>
</div>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
<label>Description</label>
<input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username" ng-minlength="5" ng-maxlength="60" required>
<font color="white">
<p ng-show="userForm.username.$error.minlength" class="help-block">
<font color="#009ACD">Description is too short.</font>
</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">
<font color="#009ACD">Description is too long.</font>
</p>
</font>
</div>
<div class="col"style="text-align: center">
<button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
type="reset"
ng-click="reset()" padding-top="true"
>
Reset
</button>
<button class="button button-block button-positive" style="display: inline-block;width:100px "
ng-click="submit()"
padding-top="true"
>
Submit
</button>
</div>
</form>
</div>
My controller
.controller('ContactCtrl', function($scope,$state,$ionicPopup, $timeout) {
$scope.showfeedback = function() {
$state.go('app.sfeedback');
};
$scope.submitForm = function(isValid) {
$scope.submitted = true;
// check to make sure the form is completely valid
if (!isValid) {
var alertPopup = $ionicPopup.alert({
title: 'Invalid data entered!',
});
} else {
var alertPopup = $ionicPopup.alert({
title: 'Feedback submitted',
});
}
};
$scope.reset = function() {
var original = $scope.user;
$scope.user= angular.copy(original)
$scope.userForm.$setPristine()
};
})
var original = $scope.user;
when resetting :
$scope.user= angular.copy(original);
$scope.userForm.$setPristine();
remove
type='reset' in <button>
here is the Angular Documentation for form controllers.
Use the following to reset dirty state
$scope.form.$setPristine();
Use the following to reset to clear validation
$scope.form.$setValidity();
There's API documentation on the FormController.
This allowed me to find that there's other methods to call such as:
$setUntouched() - which is a function I was using if the user has focused on the field, and then left the field, this clears this feature when you run it.
I created a simple form reset function which you can use too.
// Set the following in your controller for the form/page.
// Allows you to set default form values on fields.
$scope.defaultFormData = { username : 'Bob'}
// Save a copy of the defaultFormData
$scope.resetCopy = angular.copy($scope.defaultFormData);
// Create a method to reset the form back to it's original state.
$scope.resetForm = function() {
// Set the field values back to the original default values
$scope.defaultFormData = angular.copy($scope.resetCopy);
$scope.myForm.$setPristine();
$scope.myForm.$setValidity();
$scope.myForm.$setUntouched();
// in my case I had to call $apply to refresh the page, you may also need this.
$scope.$apply();
}
In your form, this simple setup will allow you to reset the form
<form ng-submit="doSomethingOnSubmit()" name="myForm">
<input type="text" name="username" ng-model="username" ng-required />
<input type="password" name="password" ng-model="password" ng-required />
<button type="button" ng-click="resetForm()">Reset</button>
<button type="submit">Log In</button>
</form>
I went with...
$scope.form.$setPristine();
$scope.form.$error = {};
Feels hacky... but a lot about angular does.
Besides... this was the only thing that worked.
I had the same problem and used the following code to completely reset the form :
$scope.resetForm = function(){
// reset your model data
$scope.user = ...
// reset all errors
for (var att in $scope.userForm.$error) {
if ($scope.userForm.$error.hasOwnProperty(att)) {
$scope.userForm.$setValidity(att, true);
}
}
// reset validation's state
$scope.userForm.$setPristine(true);
};
To me using $setPristine to reset the form is a hack.
The real solution is to keep it like it should be:
<button type="reset" ng-click="reset()"></button>
then in angular:
var original = angular.copy($scope.user);
$scope.reset = function() {
$scope.user = angular.copy(original);
};
and that's it.
Use this
<button type="button" ng-click='resetForm()'>Reset</button>
In Controller
$scope.resetForm = function(){
$scope.userForm.$dirty = false;
$scope.userForm.$pristine = true;
$scope.userForm.$submitted = false;
};
Its working for me
In case you don't have a master (dynamic models from server), and you want to reset the form but only the binded part of the model you can use this snippet:
function resetForm(form){
_.forEach(form, function(elem){
if(elem !== undefined && elem.$modelValue !== undefined){
elem.$viewValue = null;
elem.$commitViewValue();
}
});
}
And then you can use it with a standard reset button like so:
<button type="reset" ng-click="resetForm(MyForm);MyForm.$setValidity();">reset</button>
Give us your Feedback
<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
<label>Name*</label>
<input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block"><font color="#009ACD">You name is required.</font></p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty }">
<label>Email</label>
<input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block"><font color="#009ACD">Enter a valid email.</font></p>
</div>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
<label>Description</label>
<input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username" ng-minlength="5" ng-maxlength="60" required>
<font color="white"><p ng-show="userForm.username.$error.minlength" class="help-block"><font color="#009ACD">Description is too short.</font></p>
<p ng-show="userForm.username.$error.maxlength" class="help-block"><font color="#009ACD">Description is too long.</font></p>
</div>
<div class="col"style="text-align: center">
<button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
type="reset"
ng-click="reset()"padding-top="true">Reset</button>
<button class="button button-block button-positive" style="display: inline-block; width:100px" ng-click="submit()"padding-top="true">Submit</button>
</div>
</form>
I kept the type="reset" in my button. What I did was the ng-click="resetForm(userForm)" (using userFrom to match your example) and the controller defines resetForm() as
scope.resetForm = function(controller) {
controller.$commitViewValue();
controller.$setPristine();
};
Here is what happens:
When the reset button is clicked, it will bring back the original values as specified by the value attribute on the input
The $commitViewValue() will force the write of whatever is on the view presently to the $modelValue of each field (no need to iterate manually), without this the last $modelValue would still be stored rather than reset.
The $setPristine() will reset any other validation and submitted fields.
In my angular-bootstrap-validator I already had the FormController as such I didn't need to pass in the form itself.
In My Form
<form angular-validator-submit="submitReview()" name="formReview" novalidate angular-validator>
<input type="text" name="Rating" validate-on="Rating" class="form-control"
ng-model="Review.Rating" required-message="'Enter Rating'" required>
<button type="button" ng-click="reset()">Cancel</button>
</form>
app.controller('AddReview', function ($scope) {
$scope.reset= function () {
$scope.formReview.reset()
};
});
only need to call $scope.formReview.reset() where formReview is my form name.
My form is inside another scope so my solution need to use $$postDigest
$scope.$$postDigest(function() {
$scope.form.$error = {};
});
To reset the validations we have to do two things:
clear the fields
Add the following:
$scope.programCreateFrm.$dirty = false;
$scope.programCreateFrm.$pristine = true;
$scope.programCreateFrm.$submitted = false;
programCreateFrm is the name of the form.
For example:
<form name="programCreateFrm" ng-submit="programCreateFrm.$valid && createProgram(programs)" novalidate>
This code is working for me.

Categories

Resources