Reputation: 54072
using angular 1.5 and this is very basic problem
When I click reset button of form ; it gives error in console
Cannot read property '$setPristine' of undefined
below is my relevant code
<form name="loginForm" ng-controller="LoginController as vm" ng-submit="vm.login(credentials)" novalidate >
...form details ...
<button type="reset" class="btn btn-warn" ng-click="vm.reset()">Reset</button>
login
.controller('LoginController', function($scope){
var self = this;
self.reset = function () {
self.loginForm.$setPristine();
self.loginForm.$setUntouched();
};
even I tried with form="form.loginForm"
but no success
Kindly suggest what is the issue. here is my full code plunker
Upvotes: 1
Views: 574
Reputation: 4871
If you want to access your form
in your controller and you are using the controller as
syntax, just change your form name to this format: name="alias.formName"
Since you are using vm
when you declared your controller as ng-controller="LoginController as vm"
, your form should be:
<form name="vm.loginForm" ng-controller="LoginController as vm" ng-submit="vm.login(credentials)" novalidate >
Also don't forgot to change your ngMessages
block as well.
<div ng-messages="vm.loginForm.username.$error" ng-if="vm.loginForm.username.$touched">
<p ng-message="required">Your name is required.</p>
<p ng-message="minlength">Your name is too short.</p>
</div>
Updated:
Using $setPristine
only makes the form $pristine
, and it does not reset the value of your form fields. If your goal is to also reset the form field values, then you have to set self.credentails = {username: '',password: ''}
in your reset function.
Upvotes: 3
Reputation: 692151
There are several problems:
ng-controller="LoginController as vm"
, but ng-controller="LoginController"
name="loginForm"
instead of name="vm.loginForm"
Upvotes: 1