xkeshav
xkeshav

Reputation: 54072

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

Upvotes: 1

Views: 574

Answers (2)

Ana Liza Pandac
Ana Liza Pandac

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

JB Nizet
JB Nizet

Reputation: 692151

There are several problems:

  1. You're not using the same version of angular and angular-messages
  2. Your plunkr doesn't use ng-controller="LoginController as vm", but ng-controller="LoginController"
  3. You're expecting the form to be in the controller, but it's in the $scope, since you used name="loginForm" instead of name="vm.loginForm"

Upvotes: 1

Related Questions