Vlado Pandžić
Vlado Pandžić

Reputation: 5048

angular select validation and selected attribute

If I write this:

    <select name="udaljenosti_{$index}}" class="form-control" required>
       <option value="">Choose</option>
       <option ng-repeat="choice in attribute.Choices" value="{{choice.Id}}" ng-selected="choice.IsSelected==true">{{choice.Name}} </option>
     </select>

I don't get validation working. But when I write this:

 <select name="udaljenosti_{{$index}}" ng-model="attribute.Choices.Name" ng-options="item.Id as item.Name  for item in attribute.Choices" class="form-control" required ng-required="true">
       <option value="">Choose</option>
 </select>

validation is working but I don't know how to prepopulate select with selected option (IsSeletected property from the first example) This is JSON response: enter image description here

Upvotes: 0

Views: 454

Answers (2)

Rishi Prakash
Rishi Prakash

Reputation: 1779

Didn't get any error

tried your code, with predefined value in ng-model.

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
    <select   ng-model="selectedPerson" ng-options="p.first as p.last for p in people" class="form-control" required ng-required="true">
       <option value="">Choose</option>
 </select>
     {{ selectedPerson }}
  </div>
</div>

function TodoCtrl($scope) {

    $scope.people = [
        { id: 1, first: 'John', last: 'Rambo', actor: 'Silvester' },
        { id: 2, first: 'Rocky', last: 'Balboa', actor: 'Silvester' },
        { id: 3, first: 'John', last: 'Kimble', actor: 'Arnold' },
        { id: 4, first: 'Ben', last: 'Richards', actor: 'Arnold' }
    ];
    $scope.selectedPerson = 'Ben'; 

}

here is the working jsfiddle enter link description here

you just need to make sure ,than value is ng-model is right, in your case must match with what your ID AngularJS will automatically show you correct option selected in dropdown.

YOUR ERROR IS YOU ARE USING ng-model="attribute.Choices.Name , instead of ng-model="attribute.Choices.Id

Upvotes: 1

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38663

Try this code ng-selected="attribute.choice[$index].IsSelected==true"

try to use this instead of your code.

 <select name="udaljenosti_{{$index}}" ng-model="attribute.Choices.Name" 
 ng-options="item.Id as item.Name  for item in attribute.Choices"
 class="form-  control" required ng-required="true" 
 ng-selected=**"attribute.choice[$index].IsSelected==true"**>
                 <option value="">Choose</option>
                </select>

Upvotes: 0

Related Questions