简体   繁体   中英

How to set the value of an option when using ng-options in controller?

I am getting customer for given id,Customer details are name, email and type of customer {0,1}. For 0, customer will be Regular and 1 will Temporary.

I am able to show details of customer on form but but able to select the type of customer. My select options are showing {'regular', 'temporary'}, but not select any option value.

For example

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

Form is able to show name and email but not selecting 'regular' options

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>

Code is working fine without any error for angularjs 1.2.23

Just have replaced getCustomer method to object.

If it is not working then Check customer object using breakpoint and check whether it's proper or not and also check which version of angularjs you are using.

 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> 

I think you need to specify ng-selected and set it to your current customer type. If you don't specify ng-selected you'll end up with 3 options: '', 'regular', 'temporary'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM