1

I have a problem with my AngularJS application in which I have to chose the data from the dropdowns. The problem is that when the first dropdown (brands) is changed the data must be injected only into second dropdown (models), not globally, to all the others second dropdowns - as shown in the jsfiddle.

JsFiddle

I know, that the problem is in the ng-model - how to should I define the ng-model?

<div ng-controller="MyCtrl">
 <div ng-if="car" ng-repeat="car in cars">
  <br><label>{{car.name}}</label><br>
  <label>brand</label>
  <select ng-model="car.brand" ng-options="car as car.name for car in brands" ng-change="loadBrands($index)">
   <option value="">select</option>
  </select>
  <label>model</label>
  <select ng-model="car.brand.model" ng-options="car as car.model for car in models">
   <option value="">select</option>
  </select>
<button ng-click="show($index)">show</button>

Thanks.

1
  • 1
    From the JSfiddle, your function loadBrands() causes a change of the $scope.model property gobally. Why don't you attach the models to the brands as brand.models? Commented May 4, 2016 at 11:49

1 Answer 1

1

Instead of changing the $scope.models globally for all cars, you should update the models only for the selected Car:

JSFiddle with the following modifications:

  $scope.loadBrands = function(index) {
    if ($scope.cars[index].brand.name == 'audi') {
      $scope.cars[index].models = $scope.audi;
    } else {
      $scope.cars[index].models = $scope.bmw;
    }
  }

and the select for the models should be changed to:

<select ng-model="brand.model" ng-options="car as car.model for car in cars[$index].models">
  <option value="">select</option>
</select>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but it is not working corectly. If you select: car 1: audi, audi A and car 2: audi, audi B then car 1 model will chage too.
solved: changed ng-model="car.brand.model" to ng-model="brand.model" in <select ng-model="car.brand.model" ng-options="car as car.model for car in cars[$index].models">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.