AngularJS选择绑定到对象而非属性的ng-options

时间:2016-03-02 19:11:25

标签: javascript angularjs drop-down-menu

我正在尝试将选择列表绑定到ng-model状态缩写值..例如" AK"阿拉斯加初始选择显然不起作用,因为ng-model被设置为字符串而不是对象。我看了一遍,所有其他人都有这个问题,但我还没有找到一个有效的解决方案。

我的控制器有以下代码

  $scope.states =
            [
            {
                "name": "Alabama",
                "abbreviation": "AL"
            },
            {
                "name": "Alaska",
                "abbreviation": "AK"
            },
            {
                "name": "Arizona",
                "abbreviation": "AZ"
            }];

  //I want the model to be the abbreviation string
  $scope.state = "AK";

这是标记

<select class="form-control m-b" data-placeholder="Select Location" 
required=""  ng-model="state" 
ng-options="state as state.name for state in states track by state.abbreviation">
                            </select>

    <p>Selected State {{state}}!</p>

这是一个显示我正在讨论的问题

https://plnkr.co/edit/IzDY4GrOxJSaMV2MMP30

1 个答案:

答案 0 :(得分:2)

您可以使用

  

$scope.state.abbreviation

获取所选状态对象的删除。

plkr solution

OR

您可以将ng-options更改为

  

ng-options="state.abbreviation as state.name for state in states track by state.abbreviation"