angularjsangular-chosen

how to set default value for angular chosen


I want to set my angular chosen with default value from my response. also my Angular chosen dropdown values also coming from AJAX response. I tried ng-init and pointing the value with respect to index. But no luck.

HTML

   <select  ng-init="model.country = cities[currentLocationIdx]"  
chosen  ng-model="model.country"  
   ng-options=" cities.name for cities in cities" required> 
    <option value="">Select a Location</option> 
    </select>

JS:

$scope.model.country = "Bangalore";
    $scope.currentLocationIdx = $scope.cities.findIndex( city => city.name ===  $scope.model.country );

JSON:

[
  {
    "name": "South Andaman"
  },
  {
    "name": "Nicobar"
  },
  {
    "name": "Adilabad"
  },
  {
    "name": "Anantapur"
  },
  {
    "name": "Chittoor"
  },
  {
    "name": "East Godavari"
  },
  {
    "name": "Bangalore"
  }
]

Solution

  • You just need to declare your variable as obj in controller like this:

    $scope.model = {};
    

    WORKING DEMO