[英]Save a specific filed from an object inside ng-option? And set a first default value
I have an array of Objects that contain this data: 我有一个包含以下数据的对象数组:
vm.myCars= [
{
Id: 1,
name:"Ford"
},
{
Id: 2,
name:"Buick"
}
]
I want to show inside the ng-option the name of the car but when the user select a car i want to save the Id in a variable (an object). 我想在ng-option中显示汽车的名称,但是当用户选择汽车时,我想将ID保存在变量(对象)中。
<select class="form-control input-sm"
ng-model="vm.pickedCar.Id"
ng-options="i.name for i vm.myCars"></select>
I also want to set the first value inside the select box. 我也想在选择框中设置第一个值。 Any suggestions? 有什么建议么?
Use this ng-options
syntax: 使用以下ng-options
语法:
ng-model="vm.pickedCar" ng-options="i.Id as i.name for i in vm.myCars"
Then init the value in the controller: 然后在控制器中初始化值:
vm.pickedCar = 1;
See example: 参见示例:
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" } ]; });
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.