Angular form check: ng-show when at least one input is ng-invalid and ng-dirty

I have the following view in the Angular part:

<form name="submit_entry_form" id="submit_entry_form" ng-submit="submit()" ng-controller="SubmitEntryFormCtrl" novalidate > <input type="text" name="first_name" ng-model="first_name" placeholder="First Name" required/><br /> <input type="text" name="last_name" ng-model="last_name" placeholder="Last Name" required/><br /> <input type="text" name="email" ng-model="email" placeholder="Email Address" required/><br /> <input type="text" name="confirm_email" ng-model="confirm_email" placeholder="Confirm Email Address" required/><br /> <span ng-show="submit_entry_form.$invalid">Error!</span> <input type="submit" id="submit" value="Submit" /> </form> 

The problem I am facing is the bottom space, which says "Error!". I want this to be displayed ONLY if one of the inputs is "ng-dirty" and "ng-invalid". As above, the error is shown until the form is fully valid. A long-term solution would be to do something like:

 <span ng-show="submit_entry_form.first_name.$dirty && submit_entry_form.first_name.$invalid || submit_entry_form.last_name.$dirty && submit_entry_form.last_name.$invalid || submit_entry_form.email.$dirty && submit_entry_form.email.$invalid || submit_entry_form.confirm_email.$dirty && submit_entry_form.confirm_email.$invalid">Error!</span> 

This is UGLY. Any better way to do this?

+7
source share
1 answer

Method 1. Use the function in $ scope configured by your controller.

So, in order to better understand your problem, you wanted to show a message if any field in your form was invalid and $ dirty ...

Add a controller method:

 app.controller('MainCtrl', function($scope) { $scope.anyDirtyAndInvalid = function (form){ for(var prop in form) { if(form.hasOwnProperty(prop)) { if(form[prop].$dirty && form[prop].$invalid) { return true; } } } return false; }; }); 

and in your HTML:

 <span ng-show="anyDirtyAndInvalid(submit_entry_form);">Error!</span> 

Here is a demo plunker

Now all of the above, if someone entered the data in your form and did not complete it, the form itself is invalid. So I'm not sure if this is the best usability. But it should work.


Method 2: use a filter! (Recommended)

Now I recommend a filter for this kind of thing ...

The following filter performs the same actions as above, but is better suited for Angular, IMO. Also plunk.

 app.filter('anyInvalidDirtyFields', function () { return function(form) { for(var prop in form) { if(form.hasOwnProperty(prop)) { if(form[prop].$invalid && form[prop].$dirty) { return true; } } } return false; }; }); 
 <span ng-show="submit_entry_form | anyInvalidDirtyFields">Error!</span> 
+17
source

All Articles