javascript - AngularJS ng-下拉树结构的模型定义

标签 javascript html angularjs angular-ngmodel dropdown

我的 AngularJS 应用程序出现问题,我必须从下拉列表中选择数据。 问题是,当第一个下拉列表(品牌)更改时,数据必须仅注入(inject)到第二个下拉列表(模型)中,而不是全局注入(inject)到所有其他第二个下拉列表中 - 如 jsfiddle 中所示。

JsFiddle

我知道问题出在 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>

谢谢。

最佳答案

您应该仅更新所选汽车的模型,而不是全局更改所有汽车的 $scope.models:

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;
    }
  }

模型的选择应更改为:

<select ng-model="brand.model" ng-options="car as car.model for car in cars[$index].models">
  <option value="">select</option>
</select>

关于javascript - AngularJS ng-下拉树结构的模型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37026732/

相关文章:

javascript - $scope 变量不在 $rootScope.$on 内更新

javascript - 测试 Angular $emit 和 $on 事件

javascript - Three.js 使用 Node 模块的路径

javascript - removeClass 如果 addClass 单击?

Javascript/jQuery,if 和 else 语句都被执行

css - 所有屏幕分辨率的全宽 div

javascript - jQuery 支持 ":invalid"选择器

html - 带有图像的链接不会留在中间

javascript - 如何在我的 jQuery 导航菜单中正确定位箭头?

angularjs - 将指令 Controller 暴露给父 Controller