我有下面的HTML模板和一些要显示在输入中的数据。我喜欢在加载时在模板中显示这些数据

<div class="panel panel-default" ng-repeat="option in optionslist">
                    <div class="panel-body">
                        <div class="control-group">
                            <label>Airline</label>
                            <select class="form-control" ng-options="airline.id as airline.name for airline in airlinesList"
                                    ng-model="selected.airline" ng-change="selectedAirlines(airline, $index)">
                                <option value="">Choose Airline</option>
                            </select>
                        </div>
                        <div class="control-group">
                            <label>Cost</label>
                            <input type="number" class="form-control" placeholder="Cost" ng-model="selected.cost"
                                   ng-blur="travelCost(cost, $index)">
                        </div>
                        <div class="control-group">
                            <label>Discount</label>
                            <input type="number" class="form-control" placeholder="Discount" ng-model="selected.discount"
                                   ng-blur="travelDiscount(discount, $index)">
                        </div>
                    </div>
                </div>


我想在上面的模板中预先填充以下serviceData值。

$scope.optionslist = [1, 2];
$scope.selected ={};
$scope.serviceData = [
                    {
                        "airline": 3,
                        "cost": 12345,
                        "discount": 3212

                    },
                    {
                        "airline": 1,
                        "cost": 4321,
                        "discount": 213

                    }
                ];


这是ng-options列表

$scope.airlinesList = [
        {
            "id": 1,
            "name": 'Emirates Airline'
        },
        {
            "id": 2,
            "name": 'Saudi Arabian Airlines'
        },
        {
            "id": 3,
            "name": 'Qatar Airways'
        },
        {
            "id": 4,
            "name": 'AirAsia'
        }
    ];

最佳答案

您正在使用ng-repeat并将所有内容绑定到同一选定对象。选择的应该是对象数组。

$scope.selected = [{
    "airline": 3,
    "cost": 12345,
    "discount": 3212
  }, {
    "airline": 1,
    "cost": 4321,
    "discount": 213
  }];


如果按上述方式设置选定的数组,则将绑定到数组时将预先填充表格,如下所示:

 <select class="form-control" ng-options="airline.id as airline.name for airline in airlinesList"
         ng-model="selected[$index].airline" ng-change="selectedAirlines(airline, $index)">
     <option value="">Choose Airline</option>
 </select>


您需要绑定到正在使用的每个输入字段中的selected[$index]

这是一个小例子:http://plnkr.co/edit/aLQcU0Y2vgNRUpev66yg?p=preview

09-25 19:45