在ng-options上的选项上设置所选属性

时间:2016-02-02 00:58:54

标签: angularjs

问题

我有两个API返回车辆信息和车辆类型。当我进入我的车辆编辑视图时,车辆类型和其他的下拉菜单没有设置为相应的值,它们保留在"请选择一个选项"。

HTML

<select class="browser-default"
     ng-model="editedVehicle.vehicleTypeID"
     ng-options="vehicleType.name for vehicleType in vehicleTypes track by vehicleType.id">

    <option value="" disabled selected>Select a Vehicle Type</option>
</select>

控制器代码

// Get Vehicle Types
$http({
    url: '/api/vehicleType/',
    method: 'GET',
    headers: authenticationService.getAuthToken(),
}).success(function (data) {
    $scope.vehicleTypes = data;

}).error(function () {

});

// Get Vehicle
$http({
    url: '/api/vehicle/' + $routeParams.id,
    method: 'GET',
    headers: authenticationService.getAuthToken(),
}).success(function (data) {
    $scope.editedVehicle = data;

}).error(function () {

});

典型车辆类型数据响应

[
   {
      "id":1,
      "name":"Artic"
   },
   {
      "id":2,
      "name":"Rigid"
   },
   {
      "id":3,
      "name":"Van"
   }
]

典型的车辆数据响应

{  
   "$id":"1",
   "id":0,
   "vin":"",
   "registrationNumber":"",
   "fuelCapacity":,
   "grossWeight":,
   "trainWeight":,
   "colour":"Air Force blue",
   "manufacturer":"Mercedes-Benz",
   "model":"Axor",
   "vehicleType":"Rigid",
   "modelID":16,
   "vehicleTypeID":2,
   "colourID":1,
   "maintenanceVM":{  
      "$id":"2",
      "serviceDate":"18/02/2016",
      "motDate":"07/09/2016",
      "taxExpiryDate":"02/09/2016",
      "oLicenseExpiryDate":"04/02/2017"
   },
}

问题

如何确保响应,我会自动将下拉菜单设置为所需的项目。

2 个答案:

答案 0 :(得分:1)

var app = angular.module('myApp', []);

app.controller("myCtrl", function ($scope) {
    $scope.editedVehicle = {vehicleTypeID: ''};
    $scope.selectVehicleType = function(vehicleType) {
      $scope.editedVehicle.vehicleTypeID = vehicleType;
    };
    $scope.vehicleTypes = [
      {
        "id":1,
        "name":"Artic"
      },
      {
        "id":2,
        "name":"Rigid"
      },
      {
        "id":3,
        "name":"Van"
      }
   ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <select class="browser-default" ng-model="editedVehicle.vehicleTypeID"
     ng-options="vehicleType.id as vehicleType.name for vehicleType in vehicleTypes">
      <option value="" disabled selected>Select a Vehicle Type</option>
    </select>
    <button ng-click="selectVehicleType(2)">Select Rigid</button>
  </div>
</div>

答案 1 :(得分:1)

尝试:在html页面和

中创建具有空值的选项标签 选一个
<script >
var app = angular.module("app", []);

app.controller("ctrl", function ($scope) {

$scope.names = {
    car01: {
        brand: "Ford",
        model: "Mustang",
        color: "red"
    },
    car02: {
        brand: "Fiat",
        model: "500",
        color: "white"
    },
    car03: {
        brand: "Volvo",
        model: "XC90",
        color: "black"
    },

};

});