gpt4 book ai didi

javascript - 如何从 Angular 下拉列表中获取 ID?

转载 作者:行者123 更新时间:2023-12-03 06:58:47 24 4
gpt4 key购买 nike

正如您在代码中看到的,我有一个列表汽车 A、B 和 C,在 availableCars 列表中具有相应的 id。我已经从服务中选择了汽车。它不仅仅是一个对象,只是汽车名称。用户可以选择不同的汽车,但在更改时,我必须将汽车 ID 发送到其他服务。有没有最简单的方法来实现我的目标?

(function(angular) {
'use strict';
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {

$scope.carName = (function getCarNameFromService(){
return 'Car B';
})();

$scope.availableCars = [
{id: '1A', name: 'Car A'},
{id: '2B', name: 'Car B'},
{id: '3C', name: 'Car C'}
]
}]);
})(window.angular);
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-ngrepeat-select-production</title>


<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="app.js"></script>



</head>
<body ng-app="ngrepeatSelect">
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="carName">
<option ng-repeat="option in availableCars" value="{{option.name}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>selected car name = {{carName}}</tt><br/>
<tt>selected car id = ???</tt><br/>
</div>
</body>
</html>

最佳答案

您可以使用“ng-options”,而不是在选择内部的“option”元素上使用ng-repeat。 ng-options

我创建了一个plnkr来说明你的例子。部分关键代码如下:

JS

  var carName = "Car B"; //name provided to this controller 

$scope.availableCars = [
{id: '1A', name: 'Car A'},
{id: '2B', name: 'Car B'},
{id: '3C', name: 'Car C'}
]

$scope.selectedCar = $scope.availableCars.filter(function(car){
return car.name === carName;
})[0];

$scope.selectedId = $scope.selectedCar.id;

$scope.updateCar = function(id){
$scope.selectedId = id;
}

HTML

<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select ng-options="car as car.name for car in availableCars" ng-model="selectedCar" ng-change="updateCar(selectedCar.id)"></select>
</form>

注意 html 中的“ng-change”和“ng-options”。

关于javascript - 如何从 Angular 下拉列表中获取 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37150315/

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