Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Apply required attribute conditionally based on radio button value

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'?

like image 304
Swarne27 Avatar asked Jul 14 '14 10:07

Swarne27


1 Answers

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'">
like image 166
AlwaysALearner Avatar answered Sep 24 '22 06:09

AlwaysALearner