Reputation: 2298
I'm trying to update a model from a drop down menu using ng-options, and picking the already selected value using ng-selected. Here's a simplified example (and 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>
Angular
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;
};
}
So what's going on here is the drop-down options are the "val"s from $scope.Quarters, with the selected option's id being saved in $scope.Quarter.id. "submit" displays the id and val from $scope.Quarter. $scope.Quarter.id updates on submit, but not $scope.Quarter.val. Anybody know how to accomplish this?
EDIT
$scope.Quarter.extraField was added to better illustrate the problem I'm trying to solve. I need id and val to update, but I want extraField to stay the same.
Upvotes: 4
Views: 3380
Reputation: 16498
You've got small error inn your select directive please see here
View:
<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;
};
}
Upvotes: 2