javascript 在 angular.js 的选择下拉列表中绑定值和文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25236562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:13:39  来源:igfitidea点击:

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

javascriptangularjsng-optionsangular-ngmodel

提问by Salman

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.xin any $scopefunction.

由于模型设置为obj.x,我可以$scope.obj.x在任何$scope函数中使用它来访问它。

Naturally, it gives the valueof the selected option. Is there any way by which I can get selected text as well? for e.g. bind obj.xto and obj.x_textto the text of selected option.

自然地,它给出value了所选选项的 。有什么方法可以让我获得选定的文本?例如绑定obj.xobj.x_text所选选项的文本。

回答by apairet

If you bind col and not col.col_id:

如果你绑定 col 而不是 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 和 col_name:

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

回答by Manish Kr. Shukla

Why not use ng-repeat on options tag..

为什么不在选项标签上使用 ng-repeat ..

for e.g

例如

<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>