Dynamic models using ng-if - AngularJS form

b85411

Here is my code:

As you can see, this will only get displayed if q.answer == 'Fail' - that is the value of a select box further up in the page.

If "Fail" has been selected, then the user can select a defect type which will be saved into question.failure.type.

My question is, if a user selects "Fail" and then selects a defect type - and then changes "Fail" to something else. Then question.failure.type is still retained, even though the ng-if is false now. How can I make it so that question.failure.type is no longer in the model if the ng-if is false?

<div class="panel panel-danger" ng-if="q.answer == 'Fail'">
    <div class="panel-heading">
        <h3 class="panel-title">Comments</h3>
    </div>
    <div class="panel-body">
        <form novalidate name="failureForm">
            <div class="row">
                <div class="col-xs-12">
                    <select name='defect' class='form-control' ng-model='question.failure.type' ng-options='item for item in defectTypes' required>
                        <option value=''>Select a defect type...</option>
                    </select>

                    ...

Edit: added new code as requested

<div ng-repeat="q in questions" ng-show="standard.serviceType">
    <div class="panel panel-info">
        <div class="panel-heading">
            <h3 class="panel-title">{{ $index + 1 }}. <span ng-bind="q.questionText"></span></h3>
        </div>
        <div class="panel-body">
            <answer-field question="q"></answer-field>
        </div>
    </div>
    ... then the code in the example above appears
Claies

Assuming that the value of q.answer is assigned in an <input> element in your HTML, you can clear the value of question.failure.type based on any conditional expression using ng-change.

For example:

<input ng-bind='q.answer' 
       ng-change='question.failure.type =
                 (q.answer == 'Fail' ? question.failure.type : undefined)'
>

This is only a trivial example, but it is essentially setting the question.failure.type to either the value it already has or undefined, depending on if q.answer == 'Fail' or not.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related