gpt4 book ai didi

javascript - AngularJS-如何从第一个选择中选择选项来填充第二个选择?

转载 作者:行者123 更新时间:2023-11-28 18:13:29 25 4
gpt4 key购买 nike

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

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

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

现在,就像我从第一个选择中选择汽车一样,相应地,在第二个选择中仅应显示汽车,如果我选择“自行车”,则仅应在第二个选择中显示“自行车”。

请帮我解决这个问题。提前致谢。

最佳答案

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

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

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

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

关于javascript - AngularJS-如何从第一个选择中选择选项来填充第二个选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com