简体   繁体   中英

Binding both value and text in select dropdown in angular.js

I have this dropdown in my page

<select 
    ng-options="col.col_id as col.col_name for col in meta_data.x_cols"
    ng-model="obj.x">
</select>

Since the model is set to obj.x , I can access it using $scope.obj.x in any $scope function.

Naturally, it gives the value of the selected option. Is there any way by which I can get selected text as well? for eg bind obj.x to and obj.x_text to the text of selected option.

If you bind col and not col.col_id:

<select 
    ng-options="col as col.col_name for col in meta_data.x_cols track by col.col_id"
    ng-model="obj.x">
</select>

you will be able to access both col_id and col_name from $scope.obj.x:

$scope.obj.x.col_id
$scope.obj.x.col_name

Why not use ng-repeat on options tag..

for eg

<select 
    ng-options="col.col_id as col.col_name for col in meta_data.x_cols"
    ng-model="obj.x">

    <option
      ng-repeat="col in meta_data.x_cols"
      value="{{col.id}}"
    >{{col.name}}</option>

</select>

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