javascript ng-model 和下拉菜单,获取名称,而不是值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17773580/
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-27 09:33:16  来源:igfitidea点击:

ng-model and dropdown, get name, not value

javascripthtmlangularjs

提问by guiomie

I'm trying to read the selected option name/text/html in a drop down, as opposed to its value via angular.js. Here is how I do it, but this returns the value, not the name:

我正在尝试在下拉列表中读取选定的选项名称/文本/html,而不是通过 angular.js 读取它的值。这是我的操作方法,但这会返回值,而不是名称:

In my html

在我的 html

<select class="SelectCar" ng-model="SelectedCar"> 
   <option ng-repeat="car in cars" value="{{car.Guid}}">
      {{car.Name}}
   </option>
</select>

In my controller

在我的控制器中

var car = $scope.SelectedCar;

The value of "car" will be the car.Guid, but I'd like to return the car.Name instead. I can't remove the car.Guid for the value, since this Guid is used by another component in my app.

“car”的值将是 car.Guid,但我想返回 car.Name。我无法删除 car.Guid 的值,因为我的应用程序中的另一个组件使用了这个 Guid。

回答by Aaron Hickman

You need to use "as" from ng-options. It allows you to display one value while storing another. Take a look at the code block below:

您需要使用 ng-options 中的“as”。它允许您在存储另一个值的同时显示一个值。看看下面的代码块:

From my controller:

从我的控制器:

$scope.cars = [
    {name:'Nissan', guid:'1-9'},
    {name:'Toyota', guid:'1-23'},
    {name:'Ford', guid:'8-43'},
    {name:'Honda', guid:'2-6'},
    {name:'Datsun', guid:'1-55'}
];
$scope.selectedCar = $scope.cars[1].guid;

From my HTML:

从我的 HTML:

<select ng-model="selectedCar" ng-options="car.guid as car.name for car in cars"></select>
<div>
    Selected Color: {{selectedCar}}   
</div>

And here is a jsFiddle

这是一个jsFiddle