使用Angularjs为下拉列表设置不同的文本/值

Set different text/value for dropdown with Angularjs

本文关键字:文本 Angularjs 下拉列表 设置 使用      更新时间:2023-09-26

我想用AngularJS为下拉列表设置不同的文本/值。目前,通过使用以下语法,文本和值都是相同的:

<select name="flightNum" class="form-control" ng-model="model.flight"
       ng-options="v.Value as v.Text for v in flights" required></select>

我尝试过这种方法:

<select name="flightNum" class="form-control" ng-model="model.flight" 
          ng-options="v.Value as v.Text for v in flights" required>
    <option ng-repeat="v in flights" value="{{v.Value}}"> {{v.Text}}</option>
</select>

但我得到了相同的文本/值组合。我需要更改什么才能使用AngularJS?

只要您的$scope.flights设置正确,您显示的第一个语法应该可以工作。我已经设置了一个plunker来在http://plnkr.co/edit/PIXZZO81aQKj4kmngoXy?p=preview

它具有以下$scope.flights的数据结构:

  $scope.flights = [{
    value: 'val1',
    text: 'text1'
  }, {
    value: 'val2',
    text: 'text2'
  }, {
    value: 'val3',
    text: 'text3 '
  }]

然后,select基本上可以按原样编写(我在意外情况下使用了小写值和文本,但只需确保它在控制器和html之间匹配):

<select name="flightNum" class="form-control" ng-model="model.flight" ng-options="v.value as v.text for v in flights" required></select>

使用此设置,下拉列表中会填充"文本"字段中包含的值,但选择某些内容会将"值"设置为model.flight变量。你可以在上面提到的Plunker中看到这一点。

这是你想要的行为吗?如果没有,发生了什么不同/出乎意料的事情?

您需要在ng选项中添加track

<select name="flightNum" class="form-control" ng-model="model.flight"
       ng-options="v.Value as v.Text for v in flights track by v.Value" required>
</select>

就是这样。