Search code examples
javascripthtmlangularjsangularjs-directiveangular-ng-if

Execution of code which is inside ng-if when it is false


Imagine I have code like this:

<span>Do you like  bananas?</span>
<input type="radio" ng-model="likeBananas" name="likeBananas" value="yes">
<input type="radio" ng-model="likeBananas" name="likeBananas" value="no">
<div ng-if="likeBananas === 'no'">
    <label>Tell us why?</label>
    <textarea ng-model="whyNot" ng-required="likeBananas === 'no'"></textarea>
</div>

The idea is: if user don't like bananas, <textarea>with explanation is required. If user like bananas, of course it is not required and it's not shown to user. Because mandatory ot this field is dynamic, I used ng-required="likeBananas === 'no', but question is - do I really need it? Maybe simple required can do a job? Because, when ng-if is false, content of div should not be present in HTML. General question is - how Angular execute code inside elements with ng-ifs directive, from top to bottom or from bottom to top? In first case, code inside elements with ng-ifs when it's false should not be executed and, with case above, ng-required is not calculated when div is not present and maybe isn't needed. I hope you would help me with my doubts - thank you in advance.


Solution

  • No, you should use simply ng-required=true into a ng-if directive (in your case), because this directive behavior is removing/adding from the DOM the elements in it when the condition switch.

    Thus, if likeBananas !== 'no', the elements

    <label>Tell us why?</label>
    <textarea ng-model="whyNot" ng-required="likeBananas === 'no'"></textarea>
    

    are not included in the DOM, so the ng-require=true is not compiled.