gpt4 book ai didi

javascript - Angular 下拉菜单和 ng-option 的最佳实践是什么

转载 作者:行者123 更新时间:2023-11-29 21:48:59 28 4
gpt4 key购买 nike

美好的一天,我在 AngularJS 上创建了一个下拉菜单。但它返回给我的是对象而不是项目 {"deptName":"IT","id":"1"}。我只需要将 id 返回到我的表。我需要在 ng-options="item.deptName for item in department.departments"上更改什么吗查看示例:

JS

angular.module('firstApp', [])

.controller('EmpController', function() {
var vm = this;
// define a list of items
vm.employees = [{
name: 'Alex',
id: '2233',
dept: 'IT'
}, {
name: 'Scott',
id: '2244',
dept: 'IT'
}, {
name: 'Joe',
id: '2255',
dept: 'IT'
}];
})

.controller('DeptController', function() {
var vm = this;
vm.departments = [{
deptName: 'IT',
id: '1'
}, {
deptName: 'Finance',
id: '2'
}, {
deptName: 'Marketing',
id: '3'
}];
});

HTML

<div class="jumbotron">


<h1>The Selected is </h1>
<h2>{{main.employeeData.dept}}</h2>

<!-- form to add computer to the list -->
<form class="form-inline" ng-controller="DeptController as department">
<div class="form-group">
<label class="col-sm-2 control-label">Dept menu</label>
<div class="col-sm-6">
<!--<select required="true" ng-model="main.employeeData.dept" ng-options="item.deptName for item in department.departments">-->
<!--<option value="">Select Category</option>-->
<!--</select>-->

<select required="true" ng-model="main.employeeData.dept" ng-options="item.id as item.deptName for item in department.departments">
<option value="">Select Category</option>
</select>
</div>
</div>

</form>
</div>

</div>

最佳答案

你需要使用as of ng-options like item.id as item.deptName 。它将显示item。 deptName 下拉值并将 item.id 值分配给相应的选择 ng-model

标记

 <select required="true" ng-model="main.employeeData.dept" ng-options="item.id as item.deptName for item in department.departments">
<option value="">Select Category</option>
</select>

Working Plunkr这里

关于javascript - Angular 下拉菜单和 ng-option 的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128681/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com