如果源列表是对象数组,如何在 ng-model 中存储选定的值?

How to store selected value in ng-model if source list is array of objects?

我有如下对象数组:

vm.items = [{id: "1", val: "a"},{id: "2", val: "b"},{id: "3", val: "c"}]

我将它绑定到 select 选项,例如:

<select ng-model="vm.model.id" >
    <option value="">select somthing</option>
    <option ng-repeat="i in vm.items" value="{{i.id}}">{{i.val}}</option>
</select>

但是当我从下拉列表中 select 一些项目时,我得到了整个对象 {} 并且我只想要 id。 我该怎么做?

select中使用ng-modelng-options来实现这一点。

里面controller.js

$scope.selectedItem = "";

标记

<select ng-model="selectedItem " name="state"
        ng-options="item.id as item.value for item in vm.items">
    <option value="">select somthing</option>
</select>

您可以直接在 select 标签上使用 ng-options。如果您的 json 包含一个 id 和 name 变量,您可以将其指定为:

<select ng-model="vm.model.id" ng-options="i.id as i.name for i in vm.items">
    <option value="">select somthing</option>
</select>

i.id设置为选项值,i.name设置为文本