我有一个连接到数据库的简单 AngularJS 表单。
该表单在 HTML 表格上显示姓名和出生国家/地区的列表:
<table class="table table-bordered" style="max-width: 100%;" id="myAreas">
<tr ng-repeat="name in Names">
<td>{{name.FullName}}</td>
<td>
<select ng-model="selectedCountryForEdit" ng-show="editMode">
<option ng-repeat="z in countryList" value="{{z.CountryCode}}">{{z.CountryName}}</option>
</select>
<span style="display: block;" ng-show="!editMode">{{areaItem.Countries}}</span>
</td>
<td><a href="" ng-click="editMode = !editMode"><i class="fa fa-pencil" aria-hidden="true"></i></a></td>
</tr>
</table>
该表使用以下 JS/Angular 代码:
$http.get('/Home/GetNames')
.then(function (response) {
$scope.Names = response.data;
})
.catch(function (e) {
console.log("error", e);
throw e;
})
.finally(function () {
console.log("This finally block");
});
JS/Angular 正在调用 MVC 上的方法来列出数据库中的数据。
我不想包含 MVC 代码,因为它工作正常,而我的问题依赖于其他内容:
如果查看 html 表格,每行都有一个铅笔图标,它允许我显示下拉菜单而不是国家/地区。
我正在做的是用数据库中的国家/地区列表填充下拉菜单,并且我希望下拉菜单显示与所选行/名称相同的国家/地区。
我查了很多资料,没有找到解决这个问题的方法。我对 Angular 和 JS 很陌生,希望您能就此提出建议。
最佳答案
您需要将选择的ng-model
更改为Names
数组中的属性。
前任。如果名称具有 att 国家/地区,则 ng-model
而不是 selectedCountryForEdit
,将与Names
相同。
<table class="table table-bordered" style="max-width: 100%;" id="myAreas">
<tr ng-repeat="name in Names">
<td>{{name.FullName}}</td>
<td>
<select ng-model="name.country" ng-show="editMode">
<option ng-repeat="z in countryList" value="{{z.CountryCode}}">{{z.CountryName}}</option>
</select>
<span style="display: block;" ng-show="!editMode">{{areaItem.Countries}}</span>
</td>
<td><a href="" ng-click="editMode = !editMode"><i class="fa fa-pencil" aria-hidden="true"></i></a></td>
</tr>
</table>
还将建议将选择选项 ng-repeat 更改为 ng-options,因为这个选项具有更好的性能。
示例:
<select ng-model="name.country" ng-show="editMode" ng-options="z.countryCode as z.CountryName for z in countryList">
<option value="">Select...</option>
</select>
关于javascript - 编辑名称时,在 AngularJS 的下拉菜单上显示相同名称的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45741511/