我正在尝试使用ng-options从下拉菜单更新模型,并使用ng-selected选择已选择的值。这是一个简化的例子(和fiddle)。
HTML
<div ng-app>
<h2>Todo</h2>
<div ng-controller="QuarterController">
<select name="quarter" ng-model="Quarter.id" ng-options="q.id as q.val for q in Quarters">
<option ng-selected="Quarter.val===q.val"></option>
</select>
<input type="button" name="Submit" value="Submit" ng-click="submit()"/>
<br/>
<p>{{answer}}</p>
</div>
</div>
角
function QuarterController($scope) {
$scope.Quarters = [{val: 'Q1', id: 1}, {val: 'Q2', id:2}, {val:'Q3', id:3}, {val:'Q4', id:4}];
$scope.Quarter = {val: 'Q2', id: 2, extraField: 'Hello'};
$scope.submit = function() {
$scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id + $scope.Quarter.extraField;
};
}
所以这里发生的是下拉选项是来自$ scope.Quarters的“val”,所选选项的id保存在$ scope.Quarter.id中。 “submit”显示来自$ scope.Quarter的id和val。 $ scope.Quarter.id更新提交,但不是$ scope.Quarter.val。有人知道如何做到这一点吗?
修改
添加了答案 0 :(得分:2)
您的select指令中有小错误,请参阅here
查看:
<div ng-controller="QuarterController">
<select name="quarter" ng-model="Quarter" ng-options="q.val for q in Quarters">
<option value="">{{Quarter.val}}</option>
</select>
<input type="button" name="Submit" value="Submit" ng-click="submit()"/>
<br/>
<p>{{answer}}</p>
</div>
</div>
JS:
function QuarterController($scope) {
$scope.Quarters = [{
val: 'Q1',
id: 1
}, {
val: 'Q2',
id: 2
}, {
val: 'Q3',
id: 3
}, {
val: 'Q4',
id: 4
}];
$scope.Quarter = {
val: 'Q2',
id: 2
};
$scope.submit = function () {
$scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id;
};
}