Saras Arya
Saras Arya

Reputation: 3112

Unable to Initialize successive select in Angular JS 2

I have created a fiddle for showcasing the issue that in selects which are dependent on other selects for their values(I like to call them successive selects)

I am unable to assign an initial value to a successive select. Like
HTML

<select ng-model="car.brand" ng-options="brand for brand in brands" ng-change="selectedBrand(car.brand)"></select>
<select ng-model="car.model" ng-options="model.name for model in cars[carIndex]"></select>
<input type="text" ng-model="car.model.capacity">  

JS

$scope.brands = ['Ford', 'Honda', 'Hyundai', 'Mahindra',
    'Maruti Suzuki', 'Nissan', 'Renault', 'Skoda', 'Tata', 'Toyota', 'Volksvagen'
  ];
$scope.selectedBrand = function(brand) {
    console.log(brand);
    $scope.carIndex = $scope.brands.indexOf(brand);
  }
$scope.cars[0] = [{
    name: "Figo",
    capacity: 45
  }, {
    name: "Ecosport",
    capacity: 52
  }, {
    name: "Fiesta",
    capacity: 45
  }, {
    name: "Endeavour",
    capacity: 71
  }];

/*My Attempt*/
/*Successful*/
$scope.car.brand = $scope.brands[0];
/*Unsuccessful*/
 $scope.car.model = $scope.cars[0][0].name;

QUESTION
How do I initialize the second select and the input box dynamically when the first select is used?

Upvotes: 0

Views: 27

Answers (1)

Serg
Serg

Reputation: 22811

First, you should set carIndex. And car.model must be set to the type same as model in <select ng-options=".. for model in ..

 $scope.carIndex=0;
 $scope.car.brand = $scope.brands[0];
 $scope.car.model = $scope.cars[0][0];

Upvotes: 1

Related Questions