Angular $setPristine is not working - javascript

Html :
I'm using controller as syntax.
<form name="occupantDetailForm" role="form" novalidate class="form-validation">
<div class="form-group form-md-line-input form-md-floating-label no-hint">
<input class="form-control" type="text" name="LastName" ng-model="vm.occupantDetail.lastName" ng-class="{'edited':vm.occupantDetail.lastName}" maxlength="#OccupantDetail.MaxLength" required>
<label>#L("LastName")</label>
</div>
<button type="submit" class="btn btn-primary blue" ng-click="vm.saveOccupantDetail(occupantDetailForm)" ng-disabled="occupantDetailForm.$invalid"><i class="fa fa-save"></i> <span>#L("Save")</span></button>
</form>
JS :
vm.saveOccupantDetail = function (form) {
vm.occupantDetailForm = form;
createOrEditOccupantDetail();//create or edit
vm.occupantDetail = {};
vm.occupantDetailForm.$setPristine();
}
Q : I have tried many ways but it is not working ? When I use the vm.occupantDetailForm.$setUntouched(); then it works fine.But then the problem is Save button is not being disabled.Could you tell me why ? When I use the vm.occupantDetailForm.$setPristine(); only then it is not working at all.Why ? Thanks.

$setPristine only marks your form as $pristine and to actually reset the form you need, set your model to a new object.
A better explanation is given here in the link:
$setPristine not working
Below is some code which might help you:
<div ng-app="myapp">
<div ng-controller="UserCtrl">
<form name="user_form" novalidate>
<input name="name" ng-model="user.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>
Pristine: {{user_form.$pristine}}
</p>
</div>
</div>
Controller Code:
var app = angular.module('myapp', []);
function UserCtrl($scope) {
$scope.reset = function() {
$scope.user = {};
$scope.user.name = "";
$scope.user_form.$setPristine();
$scope.user = {};
}
}
A fiddle:
http://jsfiddle.net/p7e1nway/1/
Update:, can you try setting $submitted to false
$scope.occupantDetailForm.$setPristine();
$scope.occupantDetailForm.$setUntouched();
$scope.occupantDetailForm.$submitted = false;

Related

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

Angular/Ionic: Can't access value in html input field

I have the following HTML code:
<div class="list">
<label class="item item-input">
<input id="email" ng-model="email" type="text" placeholder="Email Address">
</label>
<br>
<center>
<button class="button button-positive" ng-click="getData();"> Test </button>
</center>
</div>
And the following Angular code:
$scope.getData = function() {
var emailadd = document.getElementById('email');
var url = "http://172.16.99.138/sendemail.php?emailaddress="+emailadd;
console.log(url);
};
However when I try to run the code, the console says that it can't find the variable. Would appreciate guidance here.
Note: Your code in question is wrong anyway as document.getElementById('email') will get you the dom element, this is not the value() of the element.
Still you should be doing this the "Angular Way" :
You need to define the model in your Controller like so :
$scope.email = {
text: ''
};
Then you can bind in the HTML like so :
<input type="email" name="input" ng-model="email.text" required>
Then you can use the $scope.email in your method :
$scope.getData = function() {
var url = "http://172.16.99.138/sendemail.php?emailaddress="+$scope.email.text;
console.log(url);
};
ng-model Documentation
Use this way of data binding in AngularJs,pass email as parameter in function getData()
<div class="list">
<label class="item item-input">
<input id="email" ng-model="email" type="text" placeholder="Email Address">
</label>
<br>
<center>
<button class="button button-positive" ng-click="getData(email);"> Test </button>
</center>
</div>
And in your controller
$scope.getData = function(email) {
// var emailadd = document.getElementById('email');don't use this
var url = "http://172.16.99.138/sendemail.php?emailaddress="+email;
console.log(url);
};

Form data not showing after post in AngularJS

I am trying to post a form data but the content are not updated on the UI.
The following code is working it does post the data but the tags are not updated in the {{tag.Title}}.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var new1 = data;
$scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
<div class="row" data-ng-repeat="tagsByType in consultantCv.TagsbyTypes" ng-init="init('tag',2000)">
<div class="col-md-12">
<hr />
<h2>
<i class="icons8-{{tagsByType.CssClass}}" aria-hidden="true"></i>{{tagsByType.Title}}
</h2>
<div class="tags">
<div class="input-group" ng-controller="consultantController">
<div ng-repeat="tag in tagsByType.Tags" class="tag label label-success">
{{tag.Title}}
<a class="close" href ng-click="removeTag(tag)">×</a>
</div>
<form ng-submit="saveTag(Title,tagsByType.Id)" role="form">
<input type="text" ng-model="Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>
</div>
</div>
</div>
</div>
Push your data as object with same property name.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var newData = {
Title : data,
}
$scope.consultantCv.TagsbyTypes[0].Tags.push(newData);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
Found the issue was that tagsType was not passed to the controller.
Fixed it by the following code
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(result){
TagTypeId.Tags.push(result);
$scope.consultantCv.TagsbyTypes.Tags.push(newData);
//$scope.consultantCv.TagsbyTypes[0].Tags.push(new1);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
};
<form ng-submit="saveTag(tag.Title,tagsByType)" role="form">
<input type="text" ng-model="tag.Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>

How to clear angularJS form after submit?

I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.

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