AngularJS - Apply required attribute conditionally based on radio button value
angularjs, angularjs-directive, angularjs-scope
Solution
Use `ngRequired`.
`ngRequired` adds `required` attribute and `required` validation constraint to the element when the ngRequired expression evaluates to true.
<!-- adds 'required' attribute when ngRequired expression evaluates to true -->
<input type="text" id="sno" name="sno" ng-required="citizen == 'Yes'">
Problem
I have the following in my form in-order to validate, what should happen is when user clicks citizen radio buttons 'sno' is displayed/hidden according to yes/no. But I need to remove the 'required' attribute of 'sno' when user clicks "No" simultanouely, in-order to prevent validating 'sno'. ``` <input type="radio" ng-model="citizen" value="Yes" citizen-check>Yes <input type="radio" ng-model="citizen" value="No">No <div ng-show='enableNo()'> <div id="view"> <input type="text" id="sno" name="sno" required> </div> </div> <div ng-hide='enableNo()'> <div id="view"> <input type="text" id="pno" name="pno" required> </div> </div> ``` Inside controller I have the following for show/hide feature, ``` $scope.enableNo= function() { $log.log('enableNo called'); if($scope.citizen == 'Yes') { return true; } else { return false; } } ``` How do I write a directive to remove 'required' attribute of 'sno'?