Set the required attribute for the input element if it is not hidden

I am working on a dynamic form using angular.js. Entry field

<div ng-show="condition()"> <input type="text" name="field" required> </div> 

If condition () returns false, the input field will not be displayed. But by clicking the submit button, I will get chrome, the message:

 An invalid form control with name='field' is not focusable. 

Well, the solution is to use ng-required:

 <div ng-show="condition()"> <input type="text" name="field" ng-required="condition()"> </div> 

Well, here I have to repeat the code using condition () several times.

This gets bad when you can encapsulate ng-show's:

 <div ng-show="condition1()"> <div ng-show="condition2()"> <input type="text" name="field" ng-required="condition1() && condition2()"> </div> </div> 

Is there a better way, the required tag should be there when the input is visible, and not if it is hidden.

+8
angularjs ng-show
source share
3 answers

Instead of using ng-show, use ng-if, because when you use ng-show, this element is still part of the DOM.

something like that:

 <div ng-if="condition()"> <input type="text" name="field" required> </div> 

This way you will not get an error

 An invalid form control with name='field' is not focusable. 
+13
source share

One option is to use a variable instead of calling a function.

 <div ng-show="condition1()"> <div ng-show="condition2()"> <input type="text" name="field" ng-required="isRequired"> </div> 

and in your controller you can set the isRequired variable to true or false in your conditions condition1 () and / or condition2 ().

 function myController($scope){ $scope.isRequired = false; // initialize it $scope.condition1 = condition1; $scope.condition2 = condition2; function condition1(){ var returnValue = false; // Do some testing that sets returnValue true or false $scope.isRequired = returnValue; return returnValue; } function condition2(){ var returnValue = false; // Do some testing that sets returnValue true or false $scope.isRequired = returnValue; return returnValue; } } 

Obviously, this is not bulletproof code. But this is the beginning.

+2
source share

I would advise you to use ng-if , which will remove the element from the form, or you can tell the DOM if the condition is not met. you will get a code similar to

 <div> <div> <input type="text" name="field" ng-if="condition1() && condition2()" required> </div> </div> 
+1
source share

All Articles