简体   繁体   中英

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

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.

Transform the array into object looking like this:

{
  0: 'DENTAL',
  1: 'PSYCHOLOGY'
}

and store it in separate scope variable (let's say dict ), then in template use:

{{dict[choice.department]}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM