Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the field of form angular

I have a form with some fields.
I'm validating the fields with css classes:(if the field is invalid and the user touched it, then input's 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 one or more field, there would be a danger alert.

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 has not touched any of the field, the css classes don't influence.(because user didn't touch...)
I want to add the class in the code.
Does anyone have an idea for an elegant way to do this without writing it on each field separately?

like image 269
Tzof Avatar asked Oct 30 '22 03:10

Tzof


1 Answers

A possible solution:

when you are executing your form function, add the following line into it.

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

this line will cause the ng $scope.$watch() run and apply changes if they exist. may work, may not work, read the following link for deeper understanding of the issue.

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

like image 112
Arel Sapir Avatar answered Nov 09 '22 23:11

Arel Sapir