user3700786 user3700786 - 1 year ago 413
Javascript Question

AngularJS ng-model definition for dropdown tree structure

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.


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">
<select ng-model="car.brand" ng-options="car as for car in brands" ng-change="loadBrands($index)">
<option value="">select</option>
<select ng-model="car.brand.model" ng-options="car as car.model for car in models">
<option value="">select</option>
<button ng-click="show($index)">show</button>


Answer Source

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 ($[index] == 'audi') {
      $[index].models = $;
    } else {
      $[index].models = $;

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download