简体   繁体   English

用于下拉树结构的 AngularJS ng-model 定义

[英]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.我的 AngularJS 应用程序有问题,我必须从下拉列表中选择数据。 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 所示。

JsFiddle提琴手

I know, that the problem is in the ng-model - how to should I define the ng-model?我知道,问题出在 ng-model - 我应该如何定义 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.谢谢。

Instead of changing the $scope.models globally for all cars, you should update the models only for the selected Car:与其为所有汽车全局更改$scope.models ,您应该只为选定的汽车更新模型:

JSFiddle with the following modifications : JSFiddle 进行了以下修改

  $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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM