【发布时间】:2015-09-12 03:34:23
【问题描述】:
我查看了 AngularJS 文档-https://docs.angularjs.org/api/ng/directive/ngOptions 但无法弄清楚如何根据模型定义在下拉列表中预选一个值。
请看一下这个 Plunker,HTML 视图应该在“单位下拉列表”中显示“克”作为选定值,但由于某种原因,它显示为选定的空白值。 请建议我在这里做错了什么。
http://plnkr.co/edit/5gO0bjXOx2mlPXgo7m4u?p=preview
'use strict';
var app = angular.module('myTestApp', []);
app.controller('myTestCtrl', myTestCtrl);
function myTestCtrl() {
var vm = this;
vm.message = "test"
vm.data = {
"units": [{
"id": 0,
"name": "Gram"
}, {
"id": 1,
"name": "Litre"
}, {
"id": 2,
"name": "Pound"
}]
};
vm.currentIngredient = {
"ingredientId": 1,
"ingredientName": "Salt",
"description": "Sea Salt.",
"unit": {
"id": 0,
"name": "Gram"
},
"status": true
};
vm.selectedUnit = vm.currentIngredient;
}
以下是我的观点:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<link rel="stylesheet" href="style.css">
<script src="app.js"></script>
</head>
<body ng-app='myTestApp' ng-controller='myTestCtrl as vm'>
{{vm.message}}
<div>...</div>
<div class="form-group">
<label class="col-md-2 control-label" for="inputUnit">Unit:</label>
<div class="col-md-2">
<select class="form-control" ng-model="selectedUnit" ng-options="u.id as u.name for u in vm.data.units"></select>
</div>
</div>
</body>
</html>
【问题讨论】:
-
selectedUnit在视图中为 null,因为它可以作为vm.selectedUnit使用,它具有对象作为值,但试图将 unit.id 绑定到该对象值。所以如果你使用vm.selectedUnit.unit.id那么它应该可以工作。 -
我尝试在我的视图中使用它 - vm.selectedUnit.unit.id。但它仍然默认为在 Unit DDL 中选择的空白。
标签: angularjs