Neelabh Singh
Neelabh Singh

Reputation: 2678

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':'[email protected]', '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>

Upvotes: 0

Views: 68

Answers (2)

Sarjan Desai
Sarjan Desai

Reputation: 3733

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': '[email protected]',
    '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>

Upvotes: 1

dimaj
dimaj

Reputation: 3

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'

Upvotes: 0

Related Questions