我在cars
中有以下数据。我想从下拉列表中获取所选键。就像用户选择Ford
时一样,它应该给我car01
。我想从下拉列表获得关键和价值。
我试图使用{{x}}
,但它没有显示任何内容。
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Select a car:</p>
<select ng-model="selectedCar" ng-options="x for (x, y) in cars">
</select>
<h1>You selected: {{selectedCar.brand}}</h1>
<h2>Model: {{selectedCar.model}}</h2>
<h3>Color: {{selectedCar.color}}</h3>
<p>ColorKey: {{x}}</p>
<p>Note that the selected value represents an object.</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
}
});
</script>
答案 0 :(得分:1)
像这样使用
<select ng-model="selectedCar" ng-options="x as y.brand for (x, y) in cars">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Select a car:</p>
<select ng-model="selectedCar" ng-options="x as y.brand for (x, y) in cars">
</select>
{{selectedCar}}
<h1>You selected: {{cars[selectedCar].brand}}</h1>
<h2>Model: {{cars[selectedCar].model}}</h2>
<h3>Color: {{cars[selectedCar].color}}</h3>
<p>ColorKey: {{selectedCar}}</p>
<p>Note that the selected value represents an object.</p>
</div>