2

I'm running into an interesting Angular validation issue. I need to make sure that radio buttons are selected (they might not have a default value when loaded). The values for the radio buttons are iterated over from an array using ng-repeat. This whole thing also happens inside another ng-repeat for a list of users.

The issue is that I have to set a unique/dynamic name attribute on each group of related radio buttons, otherwise selecting one will unselect others in a different row. The validation in based on the name attribute and I cannot seem to find a way to use this unique/dynamic name in the needed ng-class and ng-show expressions.

This is waht is not working: ng-show="userFormRow.service-{{$index}}.$invalid"

Here's a sample of the code in context:

<table class='table table-striped table-bordered'>
    <tbody>
      <tr ng-repeat="u in users"
          ng-form="userFormRow">
        <td>
          <!-- THIS is having an issue determining the name of this form item since I need to generate a dynamic one here-->
          <div class="form-group"
               ng-class="{'has-error': userFormRow.service-{{$index}}.$invalid }">
            <label class="control-label center-block">Service</label>
            <div class="radio-inline" ng-repeat="o in serviceOptions">
              <label>
                <!-- HERE is where I define the unique name attribute based on the index of the table repeater -->
                <input type="radio"
                       name="service-{{$parent.$index}}"
                       value="{{::o}}"
                       ng-model="u.Service"
                       ng-required="!u.Service"> {{::o}}
              </label>
            </div>

            <!-- THIS is having an issue determining the name of this form item since I need to generate a dynamic one here-->
            <p class="help-block" ng-show="userFormRow.service-{{$index}}.$invalid">A service must be selected!</p>
          </div>
        </td>
      </tr>
    </tbody>
  </table>

And here is a full code example.http://codepen.io/chrismbarr/pen/eNoGLJ?editors=101 Check the console for errors

1 Answer 1

2

You should use bracket notation to access variable object property:

ng-show="userFormRow['service-' + $index].$invalid"

and same with ngClass:

ng-class="{'has-error': userFormRow['service-' + $index].$invalid }"

Demo: http://codepen.io/anon/pen/rVbYpG?editors=100

Sign up to request clarification or add additional context in comments.

Comments

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.