Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  158] [ 6]  / answers: 1 / hits: 16035  / 11 Years ago, fri, september 13, 2013, 12:00:00

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:



enter



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.


More From » angularjs

 Answers
18

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!


[#75698] Thursday, September 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
khalilb

Total Points: 173
Total Questions: 110
Total Answers: 105

Location: Honduras
Member since Thu, Mar 23, 2023
1 Year ago
;