我有一个像$scope.years = ['1900', '1901', '1902'];
如果我使用<select ng-model="chosenYear" ng-options="choice for choice in years"></select>
我得到了
<option value="0">1900</option>
<option value="1">1901</option>
<option value="2">1902</option>
其中数组的索引变为&#39; value
&#39;选项。我怎样才能使value
和label
相等(均为1900,1902,1902等)?
similar问题有一个已接受的答案,但它根本不做这件事。
Angular版本: 1.2.16
答案 0 :(得分:4)
你想要的是<select ng-model="chosenYear" ng-options="choice as choice for choice in years"></select>
编辑:
因为上面的方法不适用于角度1.2.16
,请尝试以下
<select ng-model="chosenYear" ng-options="choice for choice in years track by choice"></select>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.years = ['1900', '1901', '1902'];
});
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="chosenYear" ng-options="choice for choice in years track by choice"></select>
</div>
</body>
</html>
&#13;
答案 1 :(得分:1)
查看this,与您的情况类似,或者您可以使用ng-repeat并动态创建值<option ng-repeat="option in selecteOptions" value="option">{{option}}</option>
答案 2 :(得分:1)
试试这个
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.years = [{
label: "1900",
value: "1900"
}, {
label: "1901",
value: "1901"
}, {
label: "1902",
value: "1902"
},
];
});
&#13;
<!DOCTYPE html>
<html>
<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 year:</p>
<select name="mySelect" id="mySelect" ng-options="option.label for option in years track by option.value" ng-model="selectedCar"></select>
<h1>You selected: {{selectedCar.label}}</h1>
</div>
</body>
</html>
&#13;
答案 3 :(得分:0)
如果您不介意使用ng-repeat,请改用:
<select ng-model="selectedItem">
<option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>