为什么这个AngularJS不会填充我的下拉列表?

时间:2016-08-19 19:32:15

标签: asp.net angularjs json

这是我的选择:

<select class="dropdownInForm" ng-model="vehicle">
    <option ng-repeat="vehicle in vehicles" value="vehicle.VehicleID">{{vehicle.VehicleName}}</option>
</select>

以下是我在角度控制器中加载数据的方法:

$http.post('VehicleEdit.aspx/GetVehicles', { vendorID: $scope.vendorID, placeID: $scope.placeID})
            .then(function (response) {
                $scope.vehicles = response.data;
                $scope.vehicle = $scope.vehicles[0];
            })

以下是response.data包含的内容:

"[{"VehicleID":1,"VehicleName":"test1","IsActive":false},{"VehicleID":1,"VehicleName":"test2","IsProgrammatic":true}]"

数据库中的拉动正在我正在Chrome中调试它,并且可以看到$ scope.vehicles填充了上面的JSON。但是,无论我尝试什么,这个下拉列表都不会填充。

我哪里错了?

编辑 -

我应该注意到我也是这样尝试的,没有任何运气:

<select class="dropdownInForm" ng-model="vehicle" ng-options="vehicle.VehicleId as vehicle.VehicleName for vehicle in vehicles"></select>

以下是重新调整JSON的WebMethod:

    [WebMethod]
    public static string GetVehicles(int placeID, int vendorID)
    {
        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

        DataSet vehiclesData = VehicleLogic.GetListOfVehicles(placeID, vendorID);

        List<Vehicle> vehicles = new List<Vehicle>();

        foreach(DataRow row in vehiclesData.Tables[0].Rows)
        {
            Vehicle vehicle = new Vehicle()
            {
                VehicleID = Convert.ToInt32(row["VehicleID"]),
                VehicleName = row["VehicleName"].ToString().Trim(),
                IsProgrammatic = Convert.ToBoolean(row["IsProgrammatic"])
            };

            vehicles.Add(vehicle);
        }

        return jsonSerializer.Serialize(vehicles);
    }

3 个答案:

答案 0 :(得分:0)

尝试使用ng-options

<select ng-model="vehicle" ng-options="k as k.VehicleName for k in vehicles" >
</select>

答案 1 :(得分:0)

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.vehicles = [{
      "VehicleID": 1,
      "VehicleName": "test1",
      "IsActive": false
    }, {
      "VehicleID": 1,
      "VehicleName": "test2",
      "IsProgrammatic": true
    }];
    $scope.vehicle = $scope.vehicles[0];
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select ng-model="vehicle" ng-options="vehicle as vehicle.VehicleName for vehicle in vehicles"></select>
  <div>
    Selected Vehicle: {{vehicle | json}}
  </div>
</div>

value不是Angular指令,因此在为{{vehicle.VehicleID}}元素设置value时必须使用<option>。但是,更好的方法是使用ng-options

<select class="dropdownInForm" ng-model="vehicle" ng-options="vehicle.VehicleID as vehicle.VehicleName for vehicle in vehicles"></select>

答案 2 :(得分:0)

尝试不对ng-model = vehicle&#34;使用相同的var名称和ng-repeat =&#34;车辆为......