Getting an angular form field

I have a form with some fields.
I check fields with css classes: (if the field is invalid and the user touched it, then enter border-color = red.)

select.ng-invalid.ng-touched, input.ng-invalid.ng-touched,textarea.ng-invalid.ng-touched { border-color: red; } 

If the user submits the form without filling out one or more fields, there will be a warning about the danger.

HTML:

  <div ng-show="formInvalid> error! </div> 

JS:

  if ($scope.pniyaForm.$valid) { $scope.formInvalid = false; ..... } else { $scope.formInvalid = true; } 

But, if the user submits the form and does not touch any field, the css classes do not affect (since the user did not touch ...)
I want to add a class to the code.
Does anyone have any ideas for an elegant way to do this without writing it to each field separately?

+5
source share
3 answers

Using ng class validation in angularjs

 <div class="form-group"> <label>Name</label> <input type="text" required ng-model="name" name="name" ng-class="{'has-error': myForm.name.$invalid}" /> </div> <div class="form-group"> <label>Age</label> <input type="text" required ng-model="age" name="age" ng-class="{'has-error': myForm.age.$invalid}" /> </div> 
+1
source

Possible Solution:

when you execute your form function, add the following line to it.

 $scope.$apply(function () {}); 

this line will call the ng $ scope. $ watch () launches and applies the changes, if they exist. may work, may not work, read the following link for a deeper understanding of the problem.

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

+1
source

If the user submits the form and does not touch any field, css classes do not affect

You need to specify the initial setpoint for ngModel and at least provide the required attribute for input.

Use ngClass to conditionally apply css classes in case some parts of the form are invalid

 <form name="myform"> <div class="form-group" ng-class="{'has-error': myform.myinput.$invalid}"> <input name="myinput" ng-model="myName" class="...." required> </div> .... </form> .... // in controller $scope.myName = "cats"; // form is valid $scope.myName = ""; // form is invalid, and the css class 'has-error' will be applied 

Then use ngDisables in your submit button to prevent submitting if the form is invalid.

 <button type="submit" ng-disabled="myform.$invalid">submit</button> 
0
source

Source: https://habr.com/ru/post/1270908/


All Articles