我查看了AngularJS文档 - https://docs.angularjs.org/api/ng/directive/ngOptions 但无法弄清楚如何根据模型定义在下拉列表中预选值。
请查看此Plunker,HTML视图应在“单位下拉列表”中将“Gram”显示为选定值,但由于某种原因,它会显示选中的空白值。 请在这里建议我做错了什么。
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>
答案 0 :(得分:0)
正如评论中所建议的那样,您不受vm.selectedUnit
属性的约束,您必须$scope.selectedUnit
,这不是一回事。此外,您没有预先选择与下拉层次结构正确匹配的值。为使这项工作有两个变化。
在HTML中,更改为vm.selectedUnit
:
<select class="form-control" ng-model="vm.selectedUnit" ng-options="u.id as u.name for u in vm.data.units"></select>
在JavaScript中,更改预选:
vm.selectedUnit = vm.currentIngredient.unit.id;
Forked Plunker:http://plnkr.co/edit/i5EyTvekhJ75yj903qrB?p=preview
答案 1 :(得分:-1)
我做了一些改变,希望你喜欢我的工作是我的插件代码
我的Html代码就在这里......
<select>
<option ng-repeat="units in vm.units">
{{units.name}}
</option>
</select>
和更改的app.js就像......
'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;
vm.units= vm.data.units;
}