0

Using angualrjs 1.3

I have a dropdown inside my ng-repeat as:

  <tr ng-repeat="c in myData">
    <td>
        <select name="type" class="form-control" ng-model="c.type" required>
             <option value="">--Select--</option>
             <option ng-repeat="type in types">{{type.text}}</option>
         </select>  
    </td>
  </tr>

How can i do required field validation of above dropdown.

I have other textbox controls in my ng-repeat where I used as below:

<td ng-class="{ 'has-error': myForm['comment_' + {{$index}}].$invalid && (myForm['comment__' + {{$index}}].$touched || myForm.$submitted) }">
        <input type="text" name="comment_{{$index}}" required ng-model="c.comment" class="form-control" />
    </td>

And the validation works, but when I try to apply same to the dropdown it does not work.

Any inputs ?

1 Answer 1

1

Angularjs is large and intelligent library which you can do everything on it, in your sample you can use ng-form and ng-options and ng-required instead common html codes and track input by $index as this sample.

with ng-form you can define each tr as a form and then you can check form validation.

var app = angular.module("app", []);

app.controller("ctrl", function($scope) {
    $scope.myData = [
      {},{}
    ]
    
    $scope.types = [1,2,3]
});
.has-error {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.20/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <table>
     <tr ng-repeat="c in myData" ng-form="x">
        <td>
          <select ng-model="c.type" ng-options="option for option in types" ng-required="true"></select>
        </td>
        <td>
           <input type="text" ng-model="c.text" ng-required="true" />
        </td>
        <td ng-class="{'has-error': x.$invalid}">
          form is valid: {{x.$valid}}
        </td>
    </tr>
  </table>
</div>

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

1 Comment

I needed to add default value as select so that user can select a value so I added this line: <option value="">Select</option> as option. I am not using ng-form here. Can I somehow highlight the td row without using this, someway like I am using in my TD above in my sample code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.