在控制器中使用ng-options时,如何设置选项的值



我正在获取给定id的客户,客户详细信息是姓名,电子邮件和客户类型{0,1}。对于0,客户为普通客户,1为临时客户。

我能够在表单上显示客户的详细信息,但是能够选择客户的类型。我的选择选项显示{'常规','临时'},但没有选择任何选项值。

例如

customer1={'name':'john', 'email':'john@gmail.com', 'customer_type':0}

表单能够显示姓名和电子邮件,但不选择'常规'选项

控制器

   $scope.customers_type=['regular','temporary'];
   //I will get details of customer
   $scope.customer=getCustomer($scope.id);
   if($scope.customer.customer_type ==0)
      $scope.customer.type=$scope.customers_type[0]     
    else
      $scope.customer.type=$scope.customers_type[1]  

 <div>
     <label for="Name">Name </label>
     <input  ng-model='customer.name' name="Name" type="text">
  </div>
  <div>
     <label for="email">Email </label>
     <input  ng-model='customer.email' name="email" type="text">
  </div>
  <div>
     <label for="enterprise">Type of type of Customer </label>
     <select ng-model='customer.type'  type="text"  ng-options="type for type in customers_type">
     </select>
  </div>

angularjs 1.2.23的代码工作正常,没有任何错误

刚刚将getCustomer方法替换为对象。

如果它不工作,那么检查客户对象使用断点并检查它是否正确,并检查您正在使用的angularjs版本。

angular.module("myApp", []).controller('MyContrl', function($scope) {
  $scope.customers_type = ['regular', 'temporary'];
  //I will get details of customer
  $scope.customer = {
    'name': 'john',
    'email': 'john@gmail.com',
    'customer_type': 0
  };
  if ($scope.customer.customer_type === 0) {
    $scope.customer.type = $scope.customers_type[0]
  } else {
    $scope.customer.type = $scope.customers_type[1]
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyContrl">
  <div>
    <label for="Name">Name</label>
    <input ng-model='customer.name' name="Name" type="text">
  </div>
  <div>
    <label for="email">Email</label>
    <input ng-model='customer.email' name="email" type="text">
  </div>
  <div>
    <label for="enterprise">Type of type of Customer</label>
    <select ng-model='customer.type' type="text" ng-options="type for type in customers_type">
    </select>
  </div>
</div>

我认为您需要指定ng-selected并将其设置为您当前的客户类型。如果你不指定ng-selected,你最终会有3个选项:",'regular', 'temporary'

最新更新