AngularJS-如何在第一次选择时填充第二个选项选项?

时间:2016-12-15 05:37:35

标签: javascript html angularjs

我是AngularJS的新手。在我的应用程序中,我有两个<select>。第二个选择必须取决于从第一个选择的选择中选择的值。 以下是我的控制器数据:

$scope.types=[{type:"Cars"},{type:"Bykes"}];

$scope.Cars= [{"id":1,"CarName":"Hundai"},{"id":2,"CarName":"Maruti"},{"id":3,"CarName":"Toyoto",}];

$scope.Bykes= [{"id":10,"BykeName":"Honda"},{"id":8,"BykeName":"Bajaj"},{"id":9,"BykeName":"TVS"}];

以下是我的HTML:

<div class="col-lg-2 top10">
    <select class="form-control select1" ng-model="selectedType" ng-init="selectedType='Cars'">
        <option ng-repeat="type in types">{{type.type}}</option>
    </select>
</div>

<div class="col-lg-3">
    <select ng-model="vehicle"  class="form-control select2"   >
        <option ng-repeat="car in Cars" value="{{car}}">{{car.CarName}}</option>
    </select>
</div>

实际上我的汽车和Bykes数据来自数据库。

现在好像我从第一个选择中选择了汽车,因此在第二个选择中只应显示汽车,如果我选择Bykes,则应在第二个选择中显示Bykes。

请帮我解决这个问题。提前做好准备。

2 个答案:

答案 0 :(得分:2)

以下是您可以执行的操作,而无需修改代码中的许多内容。

您可以使用ng-if检查所选车辆类型并相应显示相应的下拉列表。

&#13;
&#13;
var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
  function($scope) {
    $scope.types = [{
      type: "Cars"
    }, {
      type: "Bykes"
    }];

    $scope.Cars = [{
      "id": 1,
      "CarName": "Hundai"
    }, {
      "id": 2,
      "CarName": "Maruti"
    }, {
      "id": 3,
      "CarName": "Toyoto",
    }];

    $scope.Bykes = [{
      "id": 10,
      "BykeName": "Honda"
    }, {
      "id": 8,
      "BykeName": "Bajaj"
    }, {
      "id": 9,
      "BykeName": "TVS"
    }];

  }
]);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController as vm">
    <div class="col-lg-2 top10">
      <select class="form-control select1" ng-model="vm.selectedType" ng-init="vm.selectedType='Cars'">
        <option ng-repeat="type in types">{{type.type}}</option>
      </select>
    </div>

    <div class="col-lg-3" ng-if="vm.selectedType=='Cars'">
      <select ng-model="vehicle" class="form-control select2">
        <option ng-repeat="car in Cars" value="{{car}}">{{car.CarName}}</option>
      </select>
    </div>
    <div class="col-lg-3" ng-if="vm.selectedType=='Bykes'">
      <select ng-model="vehicle" class="form-control select2">
        <option ng-repeat="byke in Bykes" value="{{byke}}">{{byke.BykeName}}</option>
      </select>
    </div>
    <span>
    </span> 
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Here the answer

这里

populate第二次选择基于第一次选择

中的选项