Trying to get the initial value for a select element and instead of populating the value, it adds a weird string as seen in this image:
Here is the JavaScript code:
function appCtrl($scope){
$scope.teams = [
{teamId: 10, teamName: 'Foo'},
{teamId: 20, teamName: 'Bar'},
{teamId: 30, teamName: 'Steve'},
{teamId: 40, teamName: 'Jobs'},
{teamId: 50, teamName: 'Macs'}
];
$scope.filters = {
teamIdSelected: 20
};
}
Here is the HTML:
<div ng-app ng-controller="appCtrl">
<select class="small" ng-model="filters.teamIdSelected">
<option ng-repeat="team in teams" value="{{team.teamId}}">{{team.teamName}}</option>
</select>
Here is a jsbin to demonstrate: http://jsbin.com/EKOpAFI/1/edit
I also tried using the incredibly poorly documented select element here but I can't get it to work that way either where my teamId is the value and the teamName is the label. It always wants to put the index of the array as the value.
Any help would be greatly appreciated.
select
directive is really a bit hard to grok. Here's how it works in conjunction with ng-options
directive (which is amazingly powerful!)
<select
ng-model="filters.teamIdSelected"
ng-options="value.teamId as value.teamName for (key, value) in teams"
></select>
Don't get confused with the values generated in the DOM when inspecting the selects options with dev tools. The value
attribute always gets its index. Corresponding key values pairs still get evaluated against scope, so all you need is to update ´ng-model`.
Hope this helps!
I recommend using ng-options on the select element instead, like so:
<select class="small" ng-model="filters.teamIdSelected" ng-options="team.teamId as team.teamName for team in teams"></select>
Additionally, if you want to include a "Select Team" option:
<select class="small" ng-model="filters.teamIdSelected" ng-options="team.teamId as team.teamName for team in teams">
<option value="">Select Team</options>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With