AngularJS 'controller and form. $ Valid

I want to check if the form is valid inside the angular controller. This seems simple when using $ scope, but I can't get it to work with the controller-like syntax.

When I try to access the form. $ valid I get the error message "I can not read the property" $ valid "from undefined".

plunkr: http://plnkr.co/edit/w54i1bZVD8UMhxB4L2JX?p=preview

HTML

<div ng-app="demoControllerAs" ng-controller="MainController as main"> <form name="contactForm" novalidate> <p> <label>Email</label> <input type="email" name="email" ng-model="main.email" required /> </p> <p> <label>Message</label> <textarea name="message" ng-model="main.message" required></textarea> </p> <input type="submit" value="submit" ng-click="main.submit()" /> </form> </div> 

Js

 var app = angular.module('demoControllerAs', []); app.controller('MainController', [function () { var main = this; main.submit = function () { var isValid = main.contactForm.$valid; console.log(isValid); }; }]); 
+7
angularjs angularjs-validation
source share
4 answers

You can do it like @ ons-jjss, but if you prefer not to enter $scope in the controller, just change your form name as

 <form name="main.contactForm" novalidate> 

and it will work like a charm.

+9
source share

You need to use it like this: $scope.contactForm.$valid

EDIT

To work with the above syntax, $ scope must be run in the controller.

 app.controller('MainController', function($scope) { //code } 
+3
source share

You need to use main.contactForm in the form name attribute, after which it will be resolved. See This

 `http://plnkr.co/edit/us8MKU3LZ7pnLV66xIrv?p=preview` 
0
source share

You can pass your form as a parameter to submit the function as ng-click = "main.submit (contactForm)

and then confirm it in the controller method

-one
source share

All Articles