【问题标题】:When edit name, display the same name item on a dropdown menu in AngularJS编辑名称时,在 AngularJS 的下拉菜单中显示相同名称的项目
【发布时间】:2018-01-26 05:55:14
【问题描述】:

我有一个连接到数据库的简单 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 很陌生,希望您能就此提出建议。

【问题讨论】:

    标签: javascript angularjs html drop-down-menu


    【解决方案1】:

    需要将select的ng-model改为Names数组中的属性。 前任。如果 Names 有 att country,那么 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>
    

    【讨论】:

    • 谢谢!我会试试这个,我会回复你
    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2014-11-28
    相关资源
    最近更新 更多