AngularJS field expression expressions don't seem to work in ng-show

I am struggling with AngularJS validation. Here's the SSCCE in HTML 5 (which due to my server structure must be valid XML):

View in JSFiddle

HTML

<div ng-app=""> <form name="myForm" ng-controller="ValidationTest" novalidate="novalidate"> <input name="email" ng-model="myForm.email" type="email" required="required" /> <div> Field: <span ng-show="myForm.email.$valid">valid</span> <span ng-show="myForm.email.$invalid">invalid</span> <span ng-show="myForm.email.$pristine">pristine</span> <span ng-show="myForm.email.$dirty">dirty</span> </div> <div> Form: <span ng-show="myForm.$valid">valid</span> <span ng-show="myForm.$invalid">invalid</span> <span ng-show="myForm.$pristine">pristine</span> <span ng-show="myForm.$dirty">dirty</span> </div> </form> </div> 

CSS

 input.ng-valid { border-color: #0f0; } input.ng-invalid { border-color: #f00; } input.ng-pristine { background-color: #eef; } input.ng-dirty { background-color: #fee; } 

Javascript

 function ValidationTest($scope) {} 

When I run this script, the CSS classes applied to the form element correctly reflect its validation status, as do the ng-show directives for the form. However, the ng-show directives for the field start correctly (shown as "invalid" and "untouched"), but they all disappear as soon as I start typing in the field. As far as I can tell, I am doing this, as the documentation shows, and what is wrong?

+4
source share
1 answer

I just realized why: both the AngularJS object representing the field and the value of the field itself were bound to the same address: myForm.email . The value of the input element should be just email .

Clarification at the request of Ahmad: the expression myForm.email refers to an object created by AngularJS to represent the email field in the form myForm . This is not the actual value of the field that you must insert in the ng-model attribute of the <input> element. To do this, I just need to specify the name of the property in the area I want to use in order to save this value. So changing ng-model to only say email instead of myForm.email is a fix. The scope email property will then contain a string, which is the value entered in the field (when it is valid).

+5
source

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


All Articles