将选择选项与相关数据链接

时间:2014-12-16 15:01:57

标签: angularjs

我有一个带有item的对象department_id,它引用了一个对象数组departments。我正在尝试在表单中创建select,以便我可以选择department并将正确的id分配给item.department_id。到目前为止,我已经:

<p>{{ item.department_id }}</p>
<select name="department" class="form-control m-b">
    <option ng-repeat="department in departments">{{department.name}}</option>
</select>

这允许我选择部门,但我不知道如何将department.iditem.department_id相关联。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

使用ng-model将选择框中选定的值绑定到item.department_id

<p>{{ item.department_id }}</p>
<select name="department" class="form-control m-b" ng-model="item.department_id">
    <option ng-repeat="department in departments" value="{{department.id}}">{{department.name}}</option>
</select>

您也可以使用ng-options代替手动创建option代码:

<p>{{ item.department_id }}</p>
<select name="department" class="form-control m-b" ng-model="item.department_id" ng-options="dept.id for dept in departments"></select>