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
Binding both value and text in select dropdown in angular.js
提问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.x
in any $scope
function.
由于模型设置为obj.x
,我可以$scope.obj.x
在任何$scope
函数中使用它来访问它。
Naturally, it gives the value
of the selected option. Is there any way by which I can get selected text as well? for e.g. bind obj.x
to and obj.x_text
to the text of selected option.
自然地,它给出value
了所选选项的 。有什么方法可以让我获得选定的文本?例如绑定obj.x
到obj.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>