javascript - 在 Controller 中使用 ng-options 时如何设置选项的值?

标签 javascript angularjs

我正在获取给定 ID 的客户,客户详细信息包括客户 {0,1} 的姓名、电子邮件地址和类型。 对于 0,客户将是常规客户,1 是临时客户。

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

例如

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

表单可以显示姓名和电子邮件,但无法选择“常规”选项

Controller

   $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]  

HTML

 <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>

关于javascript - 在 Controller 中使用 ng-options 时如何设置选项的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182210/

相关文章:

angularjs - 使用 Angular 2 和 Http 对象获取网页内容

javascript - 从 AngularJS $cookies 获取值(value)

javascript - 用 JavaScript 编写,无法正确应用函数?

javascript - 如何在 jquery 中选择多个下拉列表?

javascript - 如何在内容可编辑 iframe 中创建非内容可编辑 div?

javascript - 如何知道鼠标在 DIV 中悬停在哪个位置的哪个字符

javascript - HTML Select Text 上的 jQuery val() 优先于 Value

javascript - 使用 Angular.ui Datepicker 没有显示日期

angularjs - 使用angularjs打开剑道菜单onClick

javascript - 使用 requirejs、angularamd 和 karma 时,“undefined”不是对象(评估 'app.register.service' )