How I can hide a div when the form is valid? - angularjs

I hide a div in the second form and the third form if the first form is valid. The idea is that when you click on the submit button and if this is valid hide this element.
<div class="cover" ng-hide ="form.shipping.$valid"/>
I am not very clear yet how the logic works Angular these cases, if someone here can give me an idea would appreciate.
Example the my code:
(function() {
'use strict';
var checkOut = angular
.module('checkOutPageApp', [
'ngResource',
'ngAnimate',
'ngMessages'
]);
// Global controller
checkOut.controller('globalCtrl', function($scope, $locale) {
$scope.areaStatus = false;
$scope.disabled = function() {
if ($scope.shipping.$valid) {
return true;
} else {
return false
}
}
});
// Controller for form Shipping address
checkOut.controller('CheckoutShippingCtrl', ['$scope', '$http', '$location',
function($scope, $http, $location) {
this.data = {};
var self = this;
this.submit = function(valid) {
$scope.areaStatus = false;
if (!valid) {
return;
}
self.submitting = true;
$http.post('', self.data).then(function() {
self.data = [];
$location.path('/completed');
}, function(response) {
self.submitting = false;
});
};
}
]);
}(window, window.angular));
<div class="modifyAddressShipping" ng-controller="CheckoutShippingCtrl as form">
<form id="shipping" class="shipping" name="shipping" novalidate ng-submit="form.submit(shipping.$valid)" ng-class="{'loading': form.submitting, 'is-el-dirty' : shipping.$dirty || shipping.dirty}">
<fieldset class="billing reset-style">
<div id="shipping_address" class="group-items-form active">
<div class="row collapse">
<div class="row">
<!-- / .items-form -->
<div class="large-12 columns items-form">
<label>
<input class="field field-chk" type="text" name="name" placeholder="Name" ng-model="form.data.name" required/>
</label>
<div class="error" ng-if="shipping.$submitted || shipping.name.$touched" ng-messages="shipping.name.$error">
<p class="text-msg" ng-message="required">You did not enter your name</p>
</div>
</div>
</div>
</div>
</div>
</fieldset>
<div class="chk-box">
<div class="large-24 column box-chk-btn chk-btn-sm">
<button ng-click="areaStatus = !areaStatus" type="submit" class="chk-btn button-cta" data-ng-disabled="shipping.$invalid">
Next
</button>
</div>
</div>
</form>
</div>
<div class="delivery-payment-card-chk">
<form id="delivery_payment_form" novalidate name="formDelivery" class="min-h-3333" data-ng-submit="deliveryForm(formDelivery.$valid)">
<fieldset class="billing reset-style">
<div id="delivery_payment" class="group-items-form">
<div class="large-24 column items-form">
<label for="delivery1">
<input name="delivery" type="radio" id="delivery1" checked>2nd Class Delivery</label>
<label for="delivery2">
<input name="delivery" type="radio" id="delivery2">Click & Collect</label>
<label for="delivery3">
<input name="delivery" type="radio" id="delivery3">48 Hour</label>
<label for="delivery4">
<input name="delivery" type="radio" id="delivery4">Next Working Day</label>
<label for="delivery5">
<input name="delivery" type="radio" id="delivery5">Saturday Courier Delivery</label>
<!-- / label -->
</div>
<!-- / .items-form -->
</div>
</fieldset>
<div class="chk-box">
<div class="large-24 column box-chk-btn chk-btn-sm">
<button class="chk-btn button-cta" data-ng-disabled="disabled">
Next
</button>
</div>
</div>
</form>
</div>
<div class="sd-delivery-payment-card-chk" ng-controller="CheckoutPaymentCtrl as form">
<form name="checkoutPayment" novalidate class="min-h-3333" ng-submit="form.submit(checkoutPayment.$valid)" ng-class="{loading:form.submitting}">
<fieldset class="sd-billing reset-style">
<div id="delivery_payment" class="sd-group-items-form">
<div class="large-24 columns items-form">
<label>
<input class="sd-field field-chk" type="text" ng-disabled="disabled" name="name" placeholder="Name" ng-model="form.data.name" required></input>
</label>
<div class="error" ng-if="checkoutPayment.$submitted || checkoutPayment.name.$touched" ng-messages="checkoutPayment.name.$error">
<p class="text-msg" ng-message="required">You did not enter your name</p>
</div>
</div>
<!-- / .sd-items-form -->
<div class="large-24 columns items-form">
<label>
<input type="text" id="card_number" name="cardnumber" card-data-type autocomplete="off" size="19" ng-minlength="15" maxlength="19" nd-disabled="" class="sd-field" placeholder="XXXX XXXX XXXX XXXX" ng-class="(form.data.cardnumber | checkcreditcard)" ng-model="form.data.cardnumber"
required>
<small class="checkCard" ng-class="(form.data.cardnumber | checkcreditcard)"></small>
</label>
<div class="error" ng-if="checkoutPayment.$submitted || checkoutPayment.cardnumber.$touched" ng-messages="checkoutPayment.cardnumber.$error">
<p class="text-msg" ng-message="required">You did not enter your card number</p>
</div>
</div>
<!-- / .sd-items-form -->
<div class="large-6 columns items-form">
<label>
<input id="expiry_date" maxlength="5" name="datacard" card-data-expiration ng-disabled="" class="sd-field txt-center p-l-0" ng-model="form.data.datacard" type="text" type placeholder="MM / YY" required></input>
</label>
<div class="error" ng-if="checkoutPayment.$submitted || checkoutPayment.datacard.$touched" ng-messages="checkoutPayment.datacard.$error">
<p class="text-msg" ng-message="required">Not valid date credit card</p>
</div>
</div>
<!-- / .sd-items-form -->
<div class="large-5 columns items-form">
<label>
<input name="cvv" class="sd-field txt-center p-l-0" ng-disabled="disabled" maxlength="4" ng-minlength="3" type="text" ng-pattern="/^[0-9]+$/" placeholder="CVV" ng-model="form.data.cvv" required></input>
</label>
<div class="error" ng-if="checkoutPayment.$submitted || checkoutPayment.cvv.$touched" ng-messages="checkoutPayment.cvv.$error">
<p class="text-msg" ng-message="required">Security code required</p>
</div>
<div class="error" ng-show="checkoutPayment.cvv.$error.pattern">
<p class="text-msg">Security code must contain only numbers</p>
</div>
<div class="error" ng-show="checkoutPayment.cvv.$error.minlength">
<p class="text-msg">Security code must be 3-4 digits</p>
</div>
</div>
<!-- / .sd-items-form -->
</div>
</div>
</fieldset>
<div class="sd-chk-box">
<div class="large-24 column box-chk-btn chk-btn-sm">
<button type="submit" class="sd-chk-btn button-cta" ng-disabled="!checkoutPayment.$invalid">
Place order
</button>
</div>
</div>
</form>
</div>

The following hides a form when the submit button has been pressed ONLY IF the form submitted is $valid. To work between controllers I created a variable on $rootScope to flag if the form is valid or invalid. It may be more correct to use a getter and setter function and store the variable in a service.
INDEX.HTML
<!DOCTYPE html>
<html lang="en" ng-app="msgApp">
<head>
<meta charset="utf-8"/>
</head>
<body ng-controller="MainCtrl">
<div ng-show="form1Done" ng-hide="!form1Done">
<h2>The Form has not disappeared</h2>
</div>
<div ng-show="!form1Done" ng-hide="form1Done">
<h2>The Form</h2>
<form name="userForm">
<div class="field">
<label for="userName">Enter your userName:</label>
<input type="text" name="userName" ng-model="data.userName"
ng-minlength="5" ng-maxlength="30" required />
<div ng-messages="userForm.userName.$error" ng-messages-multiple>
<!-- the required message -->
<div ng-message="required">Please enter username</div>
<div ng-message="minlength">Username is too short</div>
<div ng-message="maxlength">Username is too long</div>
<div ng-message="userName">Error with username</div>
</div>
</div>
<button type="submit" ng-click="clickBtn(userForm.$valid)">Submit</button>
</form>
</div>
<script src="http://code.angularjs.org/1.3.6/angular.js"></script>
<script src="http://code.angularjs.org/1.3.6/angular-messages.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</body>
</html>
APP.JS
angular.module('msgApp', ['ngMessages', 'msgApp.controllers'])
.run(function($rootScope) {
$rootScope.form1Done = false;
});
CONTROLLERS.JS
angular.module('msgApp.controllers', [] )
.controller('MainCtrl', function($scope, $rootScope) {
$scope.clickBtn = function(form) {
//valid form
if(form == true) {
console.log("Form is valid, $rootScope.form1Done= "+$rootScope.form1Done);
$rootScope.form1Done = true;
}
//invalid form
if(form == false) {
$rootScope.form1Done = false;
console.log("Form is invalid, $rootScope.form1Done= "+$rootScope.form1Done);
}
}
});

Related

How to reset Bootstrap Form

Here im using Bootstrap validations with AngularJs when my form is submitted the columns is reset but its shows all validation..But my aim is its should not display validations
Bootstrap
<div class="modal" id="modal1">
<div class="modal-dialog">
<div class="modal-content">
<form name="f1" novalidate ng-submit="Save(Auth.emp)">
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-sm-4">
Email
</div>
<div class="col-sm-8">
<input type="text" name="email" class="form-control" ng-model="Auth.Email" ng-class="Submitted?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.email.$dirty ||Submitted) && f1.email.$error.required">Email REq</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-4">
Password
</div>
<div class="col-sm-8">
<input type="text" name="psw" class="form-control" ng-model="Auth.Password" ng-class="Submitted?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.psw.$dirty ||Submitted) && f1.psw.$error.required">Password REq</span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="{{LoginAction}}" />
</div>
</form>
</div>
</div>
</div>
AngularCode.Js
$scope.Save = function (emp) {
if ($scope.LoginAction = "Login") {
$scope.Submitted = true;
if ($scope.isFormValid == true) {
var ss = {
Email: $scope.Auth.Email,
Password: $scope.Auth.Password,
}
var xxer = myServices.GetLogin(ss);
xxer.then(function (msg) {
$scope.msg = msg.data;
$('#modal2').modal('show')
Reset();
})
}
}
}
Reset
function Reset() {
$scope.Email = '';
$scope.Password = '';
}
I think you looking for this:
function Reset() {
$scope.Auth.Email = ''
$scope.Auth.Password = '';
}
You can set a model at the same level as the form tag and make all other inputs sub properties. Then set form model at the root level to an empty object when you click on reset. Here's a codepen.
function exampleController($scope) {
$scope.reset = function() {
$scope.form = {};
};
}
angular
.module('app', [])
.controller('exampleController', exampleController);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div class="row" ng-app="app" ng-controller="exampleController">
<form novalidate ng-model="form">
<input ng-model="form.email" type="email" />
<input ng-model="form.password" type="password" />
</form>
<button ng-click="reset()">Reset</button>
<pre>{{form}}</pre>
</div>

AngularJS Validations for multiple fields

I need one example for validations on dynamic added fields. Here is my page.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js">
</script>
<title>Add Remove in AngularJS</title>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.deleted = [];
$scope.inputs = [];
$scope.addRow = function(){
$scope.inputs.push({name:'', age:''});
};
$scope.removeRow = function(index, input){
// alert(index);
// alert(input);
$scope.deleted.push(input);
$scope.inputs.splice(index,1);
};
});
</script>
</head>
<body style="background-color: gray; margin-top: 10px; ">
<center>
<div class="row" ng-app="myApp" ng-controller="myCtrl">
<div class="col-md-6">
<div class="panel panel-flat">
<div class="panel-header">
<h4>
Person Address
<button ng-click="addRow()">Add</button>
</h4>
</div>
<div class="panel-body">
<form name="form" class="form-horizontal">
<div ng-repeat="input in inputs">
<div class="form-group" ng-class="{'has-error' : form.name.$invalid}">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" ng-model="input.name" name="name[$index]" ng-maxlength="45" ng-minlength="3"
class="form-control" ng-pattern="/^[a-zA-Z]+$/" required />
<span class="help-block" ng-show="form.name[$index].$error.pattern">Alphabet only</span>
<span class="help-block" ng-show="form.name[$index].$error.minlength">Too Short</span>
<span class="help-block" ng-show="form.name[$index].$error.maxlength">Too Long</span>
<span class="help-block" ng-show="form.name[$index].$error.required">required</span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Age</label>
<div class="col-md-10">
<input type="text" ng-model="input.age" name="age"
class="form-control" ng-pattern="/^[0-9]{0,3}$/" /><br>
<span ng-show="form.age.$invalid && form.age.$error.pattern">Number
length should be 3</span>
</div>
</div>
<button ng-click="removeRow($index, input)">Remove</button>
<hr>
</div>
</form>
</div>
</div>
</div>
<!-- inputs :{{inputs}}<br>deleted : {{deleted}} -->
</div>
</center>
</body>
</html>
You can add a fonction to you controller :
app.controller('myCtrl', function($scope) {
//...
$scope.validationFn = function () {
//do you validation here
};
then you just need to modify
<form name="form" class="form-horizontal" ng-submit="validationFn()">
Here is the answer:
<div class="panel-body"><form name="form" class="form-horizontal">
<div ng-repeat="input in inputs"><ng-form name="sfIn"><div class="form-group" >
<label class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" ng-model="input.name" name="name" ng-maxlength="45" ng-minlength="3"
class="form-control" ng-pattern="/^[a-zA-Z]+$/" required />
<span
class="help-block" ng-show="sfIn.name.$error.pattern">Alphabet only</span>
<span
class="help-block" ng-show="sfIn.name.$error.minlength">Too Short</span>
<span
class="help-block" ng-show="sfIn.name.$error.maxlength">Too Long</span>
<span
class="help-block" ng-show="sfIn.name.$touched.required || sfIn.name.$error.required ||
sfIn.name.$dirty.required">required</span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Age</label>
<div class="col-md-10">
<input type="text" ng-model="input.age" name="age"
class="form-control" ng-pattern="/^[0-9]{0,3}$/" /><br>
<span
ng-show="sfIn.age.$error.pattern">Number
length should be 3</span>
</div>
</div>
<button
ng-click="removeRow($index, input)">Remove</button>
</ng-form>
<hr>
</div>
</form>
</div>

not able to clear the whole form after pressing cancel button in AngularJs?

i am unable to clear my form in some of the fields which have more than one validation.can anyone please help?
<div class="col-lg-4 col-md-6">
<div class="form-group" data-ng-class="{ 'has-error' : vm.form.phonenumber.$invalid && (vm.form.phonenumber.$dirty || vm.form.phonenumber.$touched)}">
<label class="control-label col-md-4 col-sm-3 col-xs-12" data-i18n=" _phoneNumber_"></label>
<div class="col-md-8 col-sm-8 col-xs-10">
<input type="text" class="form-control col-md-7 col-xs-12" data-ng-model="vm.person.phoneNumber" required name="phonenumber" ng-pattern="/^[0-9]{10}$/" />
<span data-ng-show="vm.form.phonenumber.$error.required && (vm.form.phonenumber.$dirty || vm.form.phonenumber.$touched)" class="help-block" data-i18n="_phoneNumrequired_"></span>
<span class="help-block" data-ng-show="vm.form.phonenumber.$error.pattern && vm.form.phonenumber.$dirty" data-i18n="_phoneNuminvalid_"></span>
</div>
</div>
</div>
<div class="col-lg-4 col-md-6">
<div class="form-group" data-ng-class="{ 'has-error' : vm.form.mobilenumber.$invalid && (vm.form.mobilenumber.$dirty || vm.form.mobilenumber.$touched)}">
<label class="control-label col-md-4 col-sm-3 col-xs-12" data-i18n=" _mobileNumber_"></label>
<div class="col-md-8 col-sm-8 col-xs-10">
<input type="text" class="form-control col-md-7 col-xs-12" data-ng-model="vm.person.mobileNumber" required name="mobilenumber" ng-pattern="/^[0-9]{10}$/" />
<span data-ng-show="vm.form.mobilenumber.$error.required && (vm.form.mobilenumber.$dirty || vm.form.mobilenumber.$touched)" class="help-block" data-i18n="_mobileNumrequired_"></span>
<span class="help-block" data-ng-show="vm.form.mobilenumber.$error.pattern && vm.form.mobilenumber.$dirty" data-i18n="_mobileNuminvalid_"></span>
</div>
</div>
</div>`
angular function:
function cancel() { vm.person = angular.copy(vm.original); vm.form.$setPristine(); vm.form.$setUntouched(); }
this is before pressing cancel
this is after cancelling
you can see that data in email, phone and mobiles are not cleared
Hi See this working code where i am clearing the data of form.
migth be this will help
code is
//module declaration
var app = angular.module('myApp', []);
//Controller declaration
app.controller('myCtrl', function($scope) {
$scope.person = {
firstName: "John",
lastName: "Doe"
};
var oriPerson = angular.copy($scope.person);
$scope.resetForm = function() {
$scope.person = angular.copy(oriPerson);
$scope.personForm.$setPristine();
};
$scope.clearForm = function() {
$scope.person = {};
}
$scope.isPersonChanged = function() {
return !angular.equals($scope.person, oriPerson);
};
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="personForm" novalidate>
<label for="firstNameEdit">First name:</label>
<input id="firstNameEdit" type="text" name="firstName" ng-model="person.firstName" required />
<br />
<label for="lastNameEdit">Last name:</label>
<input id="lastNameEdit" type="text" name="lastName" ng-model="person.lastName" required />
<br />
<br />
<button type="button" ng-click="resetForm()" ng-disabled="!isPersonChanged()">Reset</button>
<button type="button" ng-click="clearForm()">clear</button>
</form>
</body>
<html>

Angular and Bootstrap radio buttons conflict When Editing Form

I am unable to get automatic radio button checked when I edit the User From using following Html and AngularJs Code. When I console {{changeUser}} this returns following data
{"id":1,"username":"Ramesh","password":"Ramesh1#23","role":"admin","active":"no"}. When I load the edit form I have to automatically checked the no radio button in the following code.
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form class="form-horizontal form-bordered" name="editUserForm" data-ng-submit="userEdit(changeUser)">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Username*</label>
<div class="col-md-4">
<input class="form-control" type="text" name="userName" data-ng-model="changeUser.username" value="{{ changeUser.username }}" data-ng-pattern="/^[a-z0-9_ .-]{5,15}$/i" required />
<span style="color:red" class="error" data-ng-show="editUserForm.userName.$error.pattern" >Only letters, integers, and underscores.Minimum 5 characters to maximum 15 characters.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Password*</label>
<div class="col-md-4">
<input class="form-control" type="password" name="changePassword" data-ng-model="changeUser.password" value="{{ changeUser.password}}" data-ng-pattern="usersPattern.password" required />
<span style="color:red" class="error" data-ng-show="editUserForm.changePassword.$error.pattern">Minimum of 8 characters, 1 capital letter,1 lowercase, 1 special-case and 1 numeric.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Action</label>
<div class="col-md-4">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changeUser.active" value="yes"/>
Yes
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changerUser.active" value="no"/>
No
</label>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn purple" data-ng-disabled= "editUserForm.$invalid">
<i class="fa fa-check"></i> Edit</button>
<button type="button" class="btn red" data-ng-click="cancelEdit()">Cancel</button>
</div>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
The Controller is
(function (){
"use strict";
function UsersEditController($scope, UserFactory, $http, $location) {
$scope.$on('$viewContentLoaded', function () {
App.initAjax(); // initialize core components
});
$scope.changeUser = {};
$scope.changeUser = UserFactory.get();
$scope.userEdit = function(data) {
$scope.changeUser = data;
console.log($scope.changeUser);
};
$scope.usersPattern = {
password: '((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%]).{8,20})'
};
$scope.cancelEdit = function() {
$location.path('users');
};
}
UsersEditController.$inject = ['$scope', 'UserFactory', '$http', '$location'];
angular.module('books').controller('UsersEditController', UsersEditController);
})()
And I guess this is your answer (even without js code provided :) )
https://stackoverflow.com/a/18446612/552194
You need to add ng-value and use it instead of the standard value

Why does ng-messages for form validation not work when using $rollbackViewValue

I have a form using ng-messages for form validation error messages. Im also using the new ng-model-options with $rollbackViewValue to rollback all changes to the form. Problem is ng-mesages will not work if I use the rollbackViewValue on the form.
I really like this new function in angular1.3 using ng-model-options to reset a form as I have not found anything that works as well as $rollbackViewValue()
Heres is the code and plunker
<!DOCTYPE html>
<html data-ng-app="App">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
</head>
<body>
<div class="container" data-ng-controller="formCrtl as vm">
<div class="col-lg-5">
<form name="form" novalidate="novalidate" role="form"
data-ng-submit="vm.submit()"
data-ng-model-options="{updateOn: 'submit'}" >
<!---->
<div class="form-group" data-ng-class="{ 'has-error': form.fname.$invalid && form.fname.$touched }">
<label for="fname">First Name</label>
<input type="text" required class="form-control" name="fname" id="fname" placeholder="Enter text" data-ng-model="vm.names.fname">
<div data-ng-if="form.fname.$touched" data-ng-messages="form.fname.$error">
<span class="help-block" data-ng-message="required">required field</span>
</div>
</div>
<div class="form-group" data-ng-class="{ 'has-error': form.lname.$invalid && form.lname.$touched }">
<label for="lname">Last Name</label>
<input type="text" required class="form-control" name="lname" id="lname" placeholder="Enter text" data-ng-model="vm.names.lname">
<div data-ng-if="form.lname.$touched" data-ng-messages="form.lname.$error">
<span class="help-block" data-ng-message="required">required field</span>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10 btn-group">
<button type="submit" class="btn btn-primary" data-ng-disabled="form.$invalid">Submit</button>
<button type="button" class="btn btn-default" data-ng-click="form.$rollbackViewValue()">reset</button>
<!---->
</div>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular-messages.js"></script>
<script src="scripts.js"></script>
</body>
</html>
controller
var App = angular.module("App", ['App', 'ngMessages']);
App.controller('formCrtl',function ($scope, $rootScope) {
var vm = this;
vm.names = {
fname: "Albert",
lname: "Capone"
}
});
You would need to make the form pristine and revert back the touched state as well. You can do so by calling the special functions, $setPristine() and $setUntouched() , on the formController. But it appears rollBackViewValue works with ngSubmit, but it is only to revertback during some action, (like esc key, another button). But if the form field has contraint errors it appears it updated viewvalue to nullify the entered value. You could try this way by resetting to default field values.
In your view:-
<button type="button" class="btn btn-default"
data-ng-click="vm.reset(form)">reset</button>
In your controller:-
var vm = this;
var defModel = {
fname: "Albert",
lname: "Capone"
};
vm.names = angular.copy(defModel);
vm.reset = function(form) {
form.$rollbackViewValue();
form.$setPristine(); //Set pristine state
form.$setUntouched(); //Set state from touched to untouched
vm.names = angular.copy(defModel); //reset model
}
var App = angular.module("App", ['App', 'ngMessages']);
App.controller('formCrtl', function($scope, $rootScope) {
var vm = this;
var defModel = {
fname: "Albert",
lname: "Capone"
};
vm.names = angular.copy(defModel);
vm.reset = function(form) {
form.$rollbackViewValue(); //Probably can be removed
form.$setPristine();
form.$setUntouched();
vm.names = angular.copy(defModel);
}
});
<div data-ng-app="App">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<div class="container" data-ng-controller="formCrtl as vm">
<div class="col-lg-5">
<form name="form" novalidate="novalidate" role="form" data-ng-submit="vm.submit(form)" data-ng-model-options="{updateOn: 'submit'}">
<!---->
<div class="form-group" data-ng-class="{ 'has-error': form.fname.$invalid && form.fname.$touched }">
<label for="fname">First Name</label>
<input type="text" required class="form-control" name="fname" id="fname" placeholder="Enter text" data-ng-model="vm.names.fname">
<div data-ng-if="form.fname.$touched" data-ng-messages="form.fname.$error">
<span class="help-block" data-ng-message="required">required field</span>
</div>
</div>
<div class="form-group" data-ng-class="{ 'has-error': form.lname.$invalid && form.lname.$touched }">
<label for="lname">Last Name</label>
<input type="text" required class="form-control" name="lname" id="lname" placeholder="Enter text" data-ng-model="vm.names.lname">
<div data-ng-if="form.lname.$touched" data-ng-messages="form.lname.$error">
<span class="help-block" data-ng-message="required">required field</span>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10 btn-group">
<button type="submit" class="btn btn-primary" data-ng-disabled="form.$invalid">Submit</button>
<button type="button" class="btn btn-default" data-ng-click="vm.reset(form)">reset</button>
<!---->
</div>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular-messages.js"></script>
</div>

Resources