Reputation: 11642
i have array of available select items:
// Default available date formats
$scope.dateformats = [
{
code: 'YY.MM.DD',
name: 'YY.MM.DD'
},
{
code: 'DD.MM.YY',
name: 'DD.MM.YY'
}
];
And I'm trying to default preselected value like this:
$scope.actualDateformat = $scope.dateformats[0].code;
<select ng-options="dateformat.name for dateformat in dateformats" ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
<option style="display:none" value="">{{actualDateformat}}</option>
</select>
Problem is, that "preselected" value appears in list as first option tag>
<option style="display:none" value="">{{actualDateformat}}</option>
After select of any from two remaining dynamically added items is text in first option appended with text (and value) of the selected item.
How can in solve it please?
I would like to have result like this:
<select>
<option value="YY.MM.DD">YY.MM.DD</option>
<option value="DD.MM.YY" selected>DD.MM.YY</option>
</select>
Thanks for any help.
Upvotes: 0
Views: 4078
Reputation: 1283
Here is FIDDLE
Your problem is you are selecting entire object not code field of that object.
dateformat.name for dateformat in dateFormats
label : dateformat.name
object : dateformat
dateformat.code as dateformat.name for dateformat in dateformats
label : dateformat.name
object : dateformat.code
Also I don't understand the need of option
withdisplay:none
.
You can select dateformat.code
like this.
<select ng-options="dateformat.code as dateformat.name for dateformat in dateformats" ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
</select>
Upvotes: 2
Reputation: 72857
Change:
<select ng-options="dateformat.name for dateformat in dateformats"
ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
<option style="display:none" value="">{{actualDateformat}}</option>
</select>
To:
<select ng-options="dateformat.code as dateformat.name for dateformat in dateformats"
ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)">
</select>
This way, the select should recognize the item where the dateformat.code
matches actualDateformat
.
This blog has some good examples about ng-options
.
To give you an example:
Assume:
$scope.array = [
{ key: 1, value: 'Display text 1!' },
{ key: 2, value: 'Display text 2!' },
{ key: 3, value: 'Display text 3!' }
]
Then, using the following options:
<select ng-options="item.key as item.value for item in array" ng-model="result">
Would result in:
<select ...>
<option value="1">Display text 1!</option>
<option value="2">Display text 2!</option>
<option value="3">Display text 3!</option>
</select>
$scope.result
would be set to these option elements' value
attribute.
If you initialize $scope.result
as 2
, "Display text 2!"
should be selected.
Upvotes: 1