【发布时间】:2016-03-18 09:15:39
【问题描述】:
我有一个包含 AllCountries 和 SelectedCoutry 的对象。
我想在<select> 上列出所有国家/地区,并通过 SelectedCountry 的值选择带有 ng-model 的选项。
但是combobox的默认值被选为null。
例子:
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.OBJ = {
"OBJ": {
"AllCountries": [
{
"country": "USA",
"id": 1
},
{
"country": "Mexico",
"id": 2
},
{
"country": "Canada",
"id": 3
}
],
"SelectedCountry": {
"country_id": 1,
}
}
}
$scope.AM = $scope.OBJ.OBJ;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ngPatternExample">
<div ng-controller="ExampleController">
selected country: {{AM.SelectedCountry.country_id}} <br/>
<select class="form-control" ng-model="AM.SelectedCountry.country_id">
<option value=""> --- </option>
<option ng-repeat="co in AM.AllCountries" value="{{co.id}}"> {{co.country}} </option>
</select>
</div>
</body>
(http://plnkr.co/edit/PI3tOrIMSTMwGC0rYA5q?p=preview)
p.s 一个很好的解释为什么这在 Angular 中并不总是有效会很好
【问题讨论】:
-
将相关代码贴在 SO
标签: javascript angularjs