12

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

1 Answer 1

42

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'">
Sign up to request clarification or add additional context in comments.

4 Comments

I want my validations for 'sno' not to fire when user clicks "No". it doesnt happen when using your way
given the condition it works. Thx for the explanation.
@CodeHater, have a look into same type of problem with buttons stackoverflow.com/questions/42997379/…
Good answer. I was conditionally adding the required attribute like so: ng-attr-required="ifCondition || undefined" but it didn't work. This works well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.