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

AngularJS ng-model definition for dropdown tree structure

本文关键字:模型 定义 结构 ng AngularJS      更新时间:2023-09-26

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

Js报价

我知道,问题出在ng模型上——我应该如何定义ng模型?

<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进行了以下修改:

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