pro.mean pro.mean - 5 months ago 93
AngularJS Question

form reset error in angular 1.5 with controller As syntax

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.html



<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.js



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

Answer

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.

Comments