Search code examples
angularjsangular-ngmodel

Angular get label of data-ng-options but pass value to ng-model


Id like to pass the value of the data-ng-options to the ng-model but get the label of the value to display on the span as below , How would i go about it ?

View

<tr ng-repeat="choice in vm.choices">
    <td>
        <span>@{{choice.department }}</span>
      <div class="form-group">
         <div class="input-group">
          <select data-ng-options=
                'd.value as d.label for d in vm.departments' ng-model="choice.department">
                    </select>
         </div>
      </div>
    </td>
</tr>

controller

vm.departments = [
            {value:0, label:'DENTAL'},
            {value:1, label:'PYCHOLOGY'}

          ];

id like the label ie 'DENTAL' to display on the span but pass the value ie 0 to the ng-model


Solution

  • Storing the value only in the ng-model makes no sense. Storing the object is the standard method when dealing with an array of objects in a dropdown.

    Consider the following:

    <span>@{{choice.department.value }}</span>
    <span>{{choice.department.label}}</span>
    <div class="form-group">
      <div class="input-group">
        <select data-ng-options='d.label for d in vm.departments' 
                ng-model="choice.department">
        </select>
      </div>
    </div>
    

    http://plnkr.co/edit/MGIvAAhiSsgkxSXpwTWZ?p=preview

    You have access to all the properties of the object to use for whatever you need.

    The difference here is in the way that the ng-options is structured. By not supplying an as clause, the entire object is assigned to the ng-model parameter, instead of a specific property from the object.