How to reset validation after submitting a form in AngularJS? - angularjs

I have one input field:
<input type="text" name="title" ng-model="genreData.title" class="form-control"
ng-class="{'error': addGenreForm.title.$invalid && !addGenreForm.title.$pristine}"
placeholder="Genre name" ng-minlength="minlength" required autofocus>
When I succesfully submit form this input is got class="error" after this:
$scope.genreData = {};
How can I fix it?

You've got to inject the form in the ng-submit function and then call the form's controller built in function $setPristine().
e.g.
View:
<form name="myForm" ng-submit="submitForm(myForm)">
<!--Input Fields-->
</form>
Controller:
$scope.submitForm = function(form) {
//Do what ever I have to do
//Then reset form
form.$setPristine();
}

I think setting
$scope.addGenreForm.$setPristine() and $scope.addGenreForm.$setUntouched
can work after submitting your form
Please share some plunker so I can help more if you still have any issues

Related

Reset form after ng-Submit and suppress ng-messages

I have a form which when I submit, I reinitialise it as the form has been submitted. I then show a message and stay on the same page.
However, the form's fields come up with the error messages as the form has been "touched".
Demonstrated below:
I have read some articles about how to go around this but none are working for me.
My HTML:
<form name="newPost" ng-submit="makeNewPost()">
<div class="form-group">
<input name="title" maxlength="46" minlength="2" type="text" class="form-control" ng-model="post.title" required="required">
<div ng-messages="newPost.title.$error" ng-if="newPost.title.$touched">
<div class="errorMessage" ng-message="required">Title is mandatory *</div>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-success" id="submit">
My controller code to reset the data:
var resetData = function(){
$scope.post = {};
};
resetData();
Of course there are more fields but to solve the problem, just this simple code will demonstrate it.
Any input will help. Thanks chaps!
Your resetData function should be:
$scope.resetData = function(){
$scope.post = {};
$scope.newPost.$setUntouched();
$scope.newPost.$setPristine();
}
where newPost is form name & $setUntouched, $setPristine will make form pristine just like initially loaded. Call this function in the end of submit function.

Angular: Disable button on click after required fields are filled in the form

I need to disable the submit button after clicking on the button to prevent multiple submissions but before the it has to ensure that the required fields are filled.
I tried
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<form name="newUserForm">
<input type="text" required>
<input type="text" required>
<input type="text">
<button ng-click="disableClick()" ng-disabled="isDisabled"
ng-model="isDisabled">Disable ng-click</button>
</form>
</div>
</body>
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', function($scope){
$scope.isDisabled = false;
$scope.disableClick = function() {
alert("Clicked!");
$scope.isDisabled = true;
return false;
}
}]);
but this will only disable the button without any validation
Ok, I get what you mean/want so I'll try to help and come up with some code - which is obviously missing but if it wasn't missing the necessary code, you'd have the solution :)
First, you'll have to properly write your form:
<form name="newUserForm" ng-submit="disableClick(newUserForm.$valid)" novalidate>
<input type="text" name="input1" ng-model="form.input1" required>
<input type="text" name="input2" ng-model="form.input2" required>
<input type="text" name="input3" ng-model="form.input3"> //not required
<button type="submit" ng-disabled="isDisabled">Disable ng-click</button>
</form>
so what we've got here, which you're missing:
You did name your form, but you're missing a submit, in the form as ng-submit or the button with type="submit", which will submit the form and that's when the validation happens
In order for Angular to validate your inputs, they need to have ng-model, otherwise it will not validate (HTML5 validation would, but read on)
I've added novalidate so we tell the browser "Hey, we need this validated but not by you, so do nothing", and Angular takes over
And last but not least, Angular adds a couple of properties to the form (see more here: Angular form Docs), $valid being one of them, which is set to true when all validated inputs are valid.
So this sums up the changes you needed to do to your form.
As for the Javascript part, there is just one small change:
$scope.disableClick = function(valid) {
if(valid && !$scope.isDisabled) {
$scope.isDisabled = true;
}
return false;
}
I guess the change is obvious, but I'll explain anyway - check that newUserForm.$valid (boolean) and if it's true (meaning form has passed validation) disable this button.
Of course, you'll have to add checks not to run the code on any type of submits and not just disabling the button (which can easily be re-enabled via Dev Tools), so that's why I added !$scope.isDisabled to the if statement.
Hope this answers your question :)
P.S. Here's a running demo in Plunker

Input has required but form still submits

I'm using the required attribute from HTML5 validations. I don't have an idea why the form still submits even though the html5 validates the empty input field.
Here's the Plunker link. http://plnkr.co/edit/evh0fCD5hdyoXXuxJrUy
<form name="searchUser" ng-submit="search(username)" validation>
<input type="search" placeholder="Username" ng-minlength="1" ng-model="username" required/>
<input type="submit" value="search" ng-click="search(username)" />
</form>
Of course it will submit, the required attribute will only trigger the validation in the field, it wont stop the submit. For this to work you have to do something like this:
if($scope.searchUser.$valid){
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
$scope.user = null;
}
Below plnkr:
http://plnkr.co/edit/XznoWH71arlV5RaDLJsd?p=preview
Hope it helps =)

How do I submit a form when input ng-change in AngularJS

What is the "AngularJS way" of doing a form submit when any of its inputs have been clicked (or changed)?
<form ng-submit="submit($event)" id="myForm">
<input type="checkbox" name="foo" value="bar" ng-click="???"/>
</form>
I'm tempted to use jQuery and simply doing ng-click="$('#myForm').submit()", but it's probably worth learning it properly.
I have tried doing ng-click="submit($event)", but the error here is the $event object within the scope of the input instead of the entire form (correct me if I'm wrong, this is what I'm getting from the documentation).
Well, you can do something like this for sure by triggering the AngularJS submit event:
$scope.change = function($event) {
$timeout(function() {
angular.element($event.target.form).triggerHandler('submit');
});
};
where
<input type="checkbox" name="foo" value="bar" ng-click="change($event)" />
However I think it's better to simply use the same function in ngClick as used in ngSubmit.
Demo: http://plnkr.co/edit/tJIYD9ZVjYzwA2aXJobo?p=preview
ng-change is what worked for me using a text input:
<form>
<select data-ng-model="headerName" data-ng-options="header for header in headers"
data-ng-change="calculateCorrelations()"></select>
</form>

empty form field is still being submitted when using angular form validation

The validation is being highlighted correctly, but when I click submit button, even with empty form field, the form is still being submitted (and nick value is undefined)
I tried adding novalidate to the form -- but that didn't help.
<form class="nick" ng-submit="joinChat()">
<input type="text" required name="nick" ng-model="nick" ng-minlength="2" ng-maxlength="10">
<button>Join</button>
</form>
I'm trying to follow this guide here:
http://www.ng-newsletter.com/posts/validations.html
The joinChat() function doesn't do any validation itself. As its my understanding this shouldn't be necessary when using Angular form validation.
$scope.joinChat = function(){
socket.emit('chat:join', { nick: $scope.nick });
};
Invalid input does not prevent angular form submission, instead try this:
<form class="nick" novalidate ng-submit="joinChat()" name="myform">
<input type="text" ng-required="true" name="nick" ng-model="nick" ng-minlength="2" ng-maxlength="10">
<button ng-disabled="myform.$invalid">Join</button>
</form>
Fiddle

Resources