从ng-option中的对象保存特定字段?并设置第一个默认值

时间:2017-05-17 20:26:13

标签: javascript html angularjs

我有一个包含这些数据的对象数组:

vm.myCars= [
        {
           Id: 1,
           name:"Ford"
        },
        {
           Id: 2,
           name:"Buick"
        }
  ]

我想在ng-option中显示汽车的名称,但是当用户选择汽车时我想将Id保存在变量(对象)中。

 <select class="form-control input-sm"                
                            ng-model="vm.pickedCar.Id"                           
                            ng-options="i.name for i vm.myCars"></select>

我还想在选择框中设置第一个值。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

使用此ng-options语法:

ng-model="vm.pickedCar" ng-options="i.Id as i.name for i in vm.myCars"

然后在控制器中初始化值:

vm.pickedCar = 1;

参见示例:

&#13;
&#13;
var app = angular.module('TestApp', []);

app.controller("testCtrl", function ($scope) {
    var vm = this;
    vm.pickedCar = 1;
    vm.myCars= [
        {
           Id: 1,
           name:"Ford"
        },
        {
           Id: 2,
           name:"Buick"
        }
    ];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp" ng-controller="testCtrl as vm">
    pickedCar: {{vm.pickedCar}}
    <br>
    <select class="form-control input-sm" ng-model="vm.pickedCar" 
            ng-options="i.Id as i.name for i in vm.myCars"></select>
</div>
&#13;
&#13;
&#13;