How to validate form angular with attribute in object? - angularjs

This is code we can validate in normal function:
<p>Username:<br>
<input type="text" name="username" ng-model="username" required>
<span style="color:red" ng-show="articleForm.username.$dirty && articleForm.username.$invalid">
<span ng-show="articleForm.username.$error.required">Username is required.</span>
</span>
</p>
But when I have title field that have code:
<header class="list-group-item-text">
<label>Title</label>
<input type="text" name="title" ng-model="$parent.mopost.title" class="form-control" required>
<span class="help-inline" ng-show="articleForm.$parent.mopost.title.$error.required">Required</span>
</header>
And controller:
$scope.mopost = {title:"",content1:"",content2:"",linkaudio:""};
Now validate in Angular, it does not operate. How I can validate attribute of object same above.

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<h2>Validation</h2>
<form ng-app="myApp" ng-controller="demoCtrl" name="articleForm" novalidate>
<header class="list-group-item-text">
<label for="title">Title</label>
<input id="title" type="text" name="user" ng-model="user" class="form-control" required>
<span ng-show="articleForm.user.$error.required">Username is required.</span>
</header>
<input type="submit" ng-disabled="articleForm.user.$dirty && articleForm.user.$invalid ||
articleForm.email.$dirty && articleForm.email.$invalid">
</form>
<script>
var app = angular.module('myApp', []);
app.controller('demoCtrl', function($scope) {
$scope.title = '';
});
</script>
</body>
</html>

Related

ng-disabled not working on Submit button in AngularJS 1.4.8

This is my first AngularJS contact form (new to AngularJS). I've read many posts about this problem and tried many solutions, but I can't get it. Seems simple enough but I'm stumped.
I want to disable the Submit button until the required inputs (email and comments) have been populated.
Also, the email and comments error messages display immediately on page load instead of waiting for the blur.
This is the correct js (the script I was using was from a tutorial, which I misunderstood):
angular.module('contForm', [])
.controller('contCtrl', function ($scope) {
$scope.user = {};
})
<form ng-app="contForm" ng-controller="contCtrl" name="mailForm" novalidate>
<input type="text" name="name" ng-model="user.name" size="31" maxlength="50"><br>
<input type="text" name="phone" ng-model="user.phone" size="31" maxlength="12"><br>
<span ng-show="mailForm.email.$touched && mailForm.email.$invalid">Please enter your email address. </span>
<input type="email" name="email" ng-model="user.email" size="31" maxlength="100" required><br>
<span ng-show="mailForm.contComments.$touched && mailForm.contComments.$invalid">Please enter your comments. </span>
<input type="text" name="contComments" ng-model="user.comments" required><br>
<input type="submit" name="subComments" value="SEND" ng-disabled="mailForm.$invalid">
</form>
I can't find that error, i think your source is not complete, i used cdn angularjs.
input.btn[disabled] {
background: red;
}
<!DOCTYPE html>
<html >
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form ng-app="app" ng-controller="ctrl" name="mailForm" novalidate>
<input type="text" name="name" ng-model="user.name" size="31" maxlength="50"><br>
<input type="text" name="phone" ng-model="user.phone" size="31" maxlength="12"><br>
<span ng-show="mailForm.email.$touched && mailForm.email.$invalid">Please enter your email address. </span>
<input type="email" name="email" ng-model="user.email" size="31" maxlength="100" required><br>
<span ng-show="mailForm.contComments.$touched && mailForm.contComments.$invalid">Please enter your comments. </span>
<input type="text" name="contComments" ng-model="user.comments" required><br>
<input class="btn" type="submit" name="subComments" value="SEND" ng-disabled="mailForm.$invalid">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<script>
var app = angular.module("app", []);
app.controller("ctrl", function ($scope) {
});
</script>
</body>
</html>

Email validation not working in angularjs?

this is my input
aby-saturn#gmail.com
hyphen is not working in emailid getting invalid email id
this is my ng-pattern
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input class="form-control" type="email" id="email" name="email" placeholder="Enter Email" ng-model="user.email" ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" noncapitalize required />
</div>
<div style="color: red" id="emailError"></div>
<span style="color:red;" class="email-error" ng-show="loginForm.submitted && loginForm.email.$error.required">Required</span>
<span style="color:red" class="error" ng-show="loginForm.submitted && loginForm.email.$error.pattern">Email not valid</span>
</div>
Here is a regexp for email validation.
^[\w-]+(\.[\w-]+)*#([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$
You can test this regexp here
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">
<p>Try writing in the input field:</p>
<form name="myForm">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input class="form-control" type="text" id="email" name="email" placeholder="Enter Email" ng-model="user.email" ng-pattern="/^[\w-]+(\.[\w-]+)*#([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/" noncapitalize required />
</div>
<div style="color: red" id="emailError"></div>
<span style="color:red;" class="email-error" ng-show="myForm.email.$error.required">Required</span>
<span style="color:red" class="error" ng-show="myForm.email.$error.pattern">Email not valid</span>
</div>
</form>
</body>
</html>
PLEASE RUN THE ABOVE SNIPPET
Here is a working DEMO
I guess you don't want to allow '-' to be in the email address, here is what I got using ng-pattern and if you want '-' to be allowed check 2nd example:
1) If '-' is not allowed:
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.user = {
email: 'test#test.com'
};
$scope.emailPattern = /^(([^-<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<form name="loginForm">
<div class="form-group">
<div class="input-group">
<input class="form-control" id="email" name="email" placeholder="Enter Email" ng-model="user.email" ng-pattern="emailPattern" noncapitalize required />
</div>
<div style="color: red" id="emailError">
<span style="color:red;" class="email-error" ng-show="loginForm.email.$error.required">Required</span>
<span style="color:red" class="error" ng-show="loginForm.email.$error.pattern">Email not valid, doesn't match the provided pattern</span>
</div>
</div>
</form>
</div>
2) If '-' is allowed:
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.user = {
email: 'test#test.com'
};
$scope.emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<form name="loginForm">
<div class="form-group">
<div class="input-group">
<input class="form-control" id="email" name="email" placeholder="Enter Email" ng-model="user.email" ng-pattern="emailPattern" noncapitalize required />
</div>
<div style="color: red" id="emailError">
<span style="color:red;" class="email-error" ng-show="loginForm.email.$error.required">Required</span>
<span style="color:red" class="error" ng-show="loginForm.email.$error.pattern">Email not valid, doesn't match the provided pattern</span>
</div>
</div>
</form>
</div>

In angularjs dynamic button creation is correct but validation is not correct

in my code buttons are created correctly but after typing the first row,click Add fields.the close button is disabled in first row.but i want only disable in current typing row.other close buttons are enable.
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script type="text/javascript" src="okay.js">
</script>
</head>
<body ng-app="testApp">
<div ng-controller="MainCtrl">
<form name="frm" class="form-inline" novalidate>
<div class="form-group">
<input type="string" name="cat_name" class="form-control" ng-model="cat_name" placeholder="Enter Category Name" ng-pattern="/^[a-zA-Z]*$/" required>
</div>
<div class="form-group">
<input type="text" name="cat_desc" class="form-control" ng-model="cat_desc" placeholder="Enter Your Description" ng-pattern="/^[a-zA-Z]*$/" required>
</div> <br>
<fieldset data-ng-repeat="choice in choices track by $index ">
<br>
<div class="form-group"> <input type="text" ng-model="choice.itemName" class="form-control" name="item_name" placeholder="Category Item Name" ng-pattern="/^[a-zA-Z]*$/" required>
<div class="form-group">
<input type="text" ng-model="choice.itemDesc" class="form-control" name="item_desc" placeholder="Category Description" ng-pattern="/^[a-zA-Z]*$/" required>
</div>
<div class="form-group">
<input type="number" ng-model="choice.itemView" class="form-control" name="item_count" ng-pattern="/^[0-9]/"placeholder="Category Item View Count" required>
<p class="help-block" ng-show="frm.item_count.$error.pattern">numbers only allowed</p>
<select id="country" ng-model="choice.states" name="state" ng-options="country for (country, states) in countries">
</div>
<div class="form-group">
<option value=''>Choose</option>
</select>City:
<select id="state" ng-disabled="!choice.states" name="city" ng-model="one">
<option value="">Choose</option>
<option ng-repeat="state in choice.states" value="{{state.id}}">{{state.city}}</option>
</select>
</div>
<button ng-click="removeChoice()" class="remove btn btn-danger" ng-disabled="!frm.item_name.$dirty||!frm.item_desc.$dirty||!frm.item_count.$dirty||!frm.state.$dirty||!frm.city.$dirty||frm.item_name.$invalid||frm.item_desc.$invalid">close</button>
</fieldset>
<br>
<button class="addfields btn btn-success" ng-click="addNewChoice()" ng-disabled="!frm.item_name.$dirty||!frm.item_desc.$dirty||!frm.item_count.$dirty||!frm.state.$dirty||!frm.city.$dirty||frm.item_name.$invalid||frm.item_desc.$invalid">Add fields</button>
<button class="addfields btn btn-success" ng-disabled="!frm.item_name.$dirty||!frm.item_desc.$dirty||!frm.item_count.$dirty||!frm.state.$dirty||!frm.city.$dirty||frm.item_name.$invalid||frm.item_desc.$invalid " >Save</button>
<span class="help-block" style="color:red"ng-show="frm.cat_desc.$error.pattern" style:"color:red">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red"ng-show="frm.item_desc.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red"ng-show="frm.cat_name.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block"style="color:red" ng-show="frm.item_name.$error.pattern">ERROR:<BR/>text only allowed</span > </div>
<div id="choicesDisplay">
{{ newItemNo }}
</div>
</form>
</div>
</body>
</html>
okay. js (angular File)
var app=angular.module('testApp', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
$scope.choices.splice(this.$index,1);
};
$scope.countries = {
'Andhra': [{
'id': '01',
'city': "Guntur"
}, {
'id': '02',
'city': "Hyderabad"
}],
'Tamilnadu': [{
'id': '03',
'city': "CBE"
}, {
'id': '04',
'dep': "Trichy"
}]
};
});
You had a few issues in your HTML that I cleaned up but primarily your issue was that you needed to perform your validation on just the current row. So you can add an ng-form attribute along with your ng-repeat to create a scope per row. The resulting HTL looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script type="text/javascript" src="okay.js"></script>
</head>
<body ng-app="testApp">
<div ng-controller="MainCtrl">
<form name="frm" class="form-inline" novalidate>
<div class="form-group">
<input type="string" name="cat_name" class="form-control" ng-model="cat_name" placeholder="Enter Category Name" ng-pattern="/^[a-zA-Z]*$/" required>
</div>
<div class="form-group">
<input type="text" name="cat_desc" class="form-control" ng-model="cat_desc" placeholder="Enter Your Description" ng-pattern="/^[a-zA-Z]*$/" required>
</div>
<br>
<fieldset data-ng-repeat="choice in choices track by $index" ng-form="formChoice">
<br>
<div class="form-group">
<input type="text" ng-model="choice.itemName" class="form-control" name="item_name" placeholder="Category Item Name" ng-pattern="/^[a-zA-Z]*$/" required>
</div>
<div class="form-group">
<input type="text" ng-model="choice.itemDesc" class="form-control" name="item_desc" placeholder="Category Description" ng-pattern="/^[a-zA-Z]*$/" required>
</div>
<div class="form-group">
<input type="number" ng-model="choice.itemView" class="form-control" name="item_count" ng-pattern="/^[0-9]/" placeholder="Category Item View Count" required>
<p class="help-block" ng-show="formChoice.item_count.$error.pattern">numbers only allowed</p>
<select id="country" ng-model="choice.states" name="state" ng-options="country for (country, states) in countries"></select>
</div>
<div class="form-group">
<option value=''>Choose</option>
City:
<select id="state" ng-disabled="!choice.states" name="city" ng-model="one">
<option value="">Choose</option>
<option ng-repeat="state in choice.states" value="{{state.id}}">{{state.city}}</option>
</select>
</div>
<button ng-click="removeChoice()" class="remove btn btn-danger" ng-disabled="!formChoice.item_name.$dirty||!formChoice.item_desc.$dirty||!formChoice.item_count.$dirty||!formChoice.state.$dirty||!formChoice.city.$dirty||formChoice.item_name.$invalid||formChoice.item_desc.$invalid">close</button>
</fieldset>
<br>
<button class="addfields btn btn-success" ng-click="addNewChoice()" ng-disabled="frm.$invalid">Add fields</button>
<button class="addfields btn btn-success" ng-disabled="!frm.item_name.$dirty||!frm.item_desc.$dirty||!frm.item_count.$dirty||!frm.state.$dirty||!frm.city.$dirty||frm.$invalid||frm.item_desc.$invalid ">Save</button>
<span class="help-block" style="color:red" ng-show="frm.cat_desc.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red" ng-show="frm.item_desc.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red" ng-show="frm.cat_name.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red" ng-show="frm.item_name.$error.pattern">ERROR:<BR/>text only allowed</span >
<div id="choicesDisplay">{{ newItemNo }}</div>
</form>
</div>
</body>
</html>

angularjs form not working when ng-app and ng-controller is declared in form tag

When I declare the ng-app and ng-controller the form does not do validation.
If I remove them then the form does basic validation, but I want to use controller logic to perform username and password validation and routing, which I cant use (as ng-controller is removed).
What I am missing?
<html ng-app>
<head>
<title>My Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script type="text/javascript">
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
</script>
<script>
<script>
var app = angular.module('myapp', []);
app.controller('loginCtrl', function($scope, $location){
$scope.loginCheck = function(){
var uname = $scope.user.name;
var pwd = $scope.user.password;
if ( uname == 'admin' && pwd =='admin123'){
window.location.hash='#/dashboard';
$location.path('/dashboard');
}
else $location.path('/about')
};
});
</script>
<body>
<h3 align="center">Loginn</h3>
<form name="form" class="login" ng-app='myapp' ng-controller = 'loginCtrl' >
<input placeholder="User Name"
name="name" ng-model="user.name" class="login-input" ng-model-options="{updateOn:'blur'}"
required pattern=".{3,}" />
<div class="error-message" ng-show="form.name.$invalid && !form.name.$pristine">
We need a name with 3 chars or more.
</div>
<br>
<input placeholder="E-mail"
name="email" ng-model="user.email" class="login-input" ng-model-options="{updateOn:'blur'}"
required type="email" />
<div class="error-message"
ng-show="form.email.$invalid && !form.email.$pristine">
We need a valid e-mail address.
</div>
<br>
<input type="password" class="login-input" ng-model="user.password" name="uPassword" required placeholder='Password' ng-minlength="6" ng-maxlength="15" title="6 to 15 characters" />
<span class="error" ng-show="form.uPassword.$dirty && form.uPassword.$error.minlength">Too short</span>
<span ng-show="form.uPassword.$dirty && form.uPassword.$error.required">Password required.</span><br />
<input type="password" class="login-input" ng-model="user.confirmpassword" name="ucPassword" required placeholder='Confirm Password' ng-minlength="6" ng-maxlength="15" title="6 to 15 characters" />
<span class="error" ng-show="form.ucPassword.$dirty && form.ucPassword.$error.minlength">Too short</span>
<span ng-show="form.ucPassword.$dirty && form.ucPassword.$error.required">Retype password.</span>
<div ng-show="(form.uPassword.$dirty && form.ucPassword.$dirty) && (user.password != user.confirmpassword)">
<span>Password mismatched</span>
</div>
<br>
<input type="submit" value ="Submit " ng-click="loginCheck()" ng-disabled="form.$invalid"/>
</form>
</body>
How can I add/specify ng-controller and ng-app in this form?
You have many problems in you app :
first line : <html ng-app>
remove ng-app, as said in the comment you can only have one ng-app tag
2 <script> in a row :
Here :
<script>
<script>
var app = angular.module('myapp', []);
JQuery should be inserted before angular, and should be inserted this way :
Here :
<script src='//code.jquery.com/jquery-latest.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
Please find bellow a working example :
<html>
<head>
<title>My Angular App</title>
<script src='//code.jquery.com/jquery-latest.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.controller('loginCtrl', function($scope, $location) {
$scope.loginCheck = function() {
var uname = $scope.user.name;
var pwd = $scope.user.password;
if (uname == 'admin' && pwd == 'admin123') {
window.location.hash = '#/dashboard';
$location.path('/dashboard');
} else {
$location.path('/about');
}
};
});
</script>
</head>
<body ng-app="myapp" ng-controller="loginCtrl">
<form name="form" class="login">
<input placeholder="User Name" name="name" ng-model="user.name" class="login-input" ng-model-options="{updateOn:'blur'}" required pattern=".{3,}" />
<div class="error-message" ng-show="form.name.$invalid && !form.name.$pristine">
We need a name with 3 chars or more.
</div>
<input placeholder="E-mail" name="email" ng-model="user.email" class="login-input" ng-model-options="{updateOn:'blur'}" required type="email" />
<div class="error-message" ng-show="form.email.$invalid && !form.email.$pristine">
We need a valid e-mail address.
</div>
<input type="password" class="login-input" ng-model="user.password" name="uPassword" required placeholder='Password' ng-minlength="6" ng-maxlength="15" title="6 to 15 characters" />
<span class="error" ng-show="form.uPassword.$dirty && form.uPassword.$error.minlength">Too short</span>
<span ng-show="form.uPassword.$dirty && form.uPassword.$error.required">Password required.</span>
<br />
<input type="password" class="login-input" ng-model="user.confirmpassword" name="ucPassword" required placeholder='Confirm Password' ng-minlength="6" ng-maxlength="15" title="6 to 15 characters" />
<span class="error" ng-show="form.ucPassword.$dirty && form.ucPassword.$error.minlength">Too short</span>
<span ng-show="form.ucPassword.$dirty && form.ucPassword.$error.required">Retype password.</span>
<div ng-show="(form.uPassword.$dirty && form.ucPassword.$dirty) && (user.password != user.confirmpassword)">
<span>Password mismatched</span>
</div>
</form>
</body>

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